how to show the draws in count using mysql? - mysql

I am making a voting system in visual basic, I'm struggling to write the right query for identifying the max vote count and also showing the the same vote count, what I mean is the draw in the candidates, how can I identify if there are draws in the election... here is my code
Private Sub president()
Dim cmd1 As New MySqlCommand("SELECT MAX(VOTECOUNT) as MV FROM candidates WHERE POSITION = 'PRESIDENT'", con)
Dim rd1 As MySqlDataReader
con.Open()
rd1 = cmd1.ExecuteReader()
If rd1.Read() Then
MV = rd1("MV").ToString
End If
con.Close()
rd1.Dispose()
Dim cmd As New MySqlCommand("SELECT CONCAT(FIRSTNAME,' ',MIDDLENAME,' ',LASTNAME) AS FULLNAME,POSITION, VOTECOUNT FROM candidates WHERE POSITION = 'PRESIDENT' AND VOTECOUNT = '" & MV & "'", con)
Dim rd As MySqlDataReader
con.Open()
rd = cmd.ExecuteReader()
While rd.Read()
TextBox1.Text = (rd("FULLNAME"))
End While
rd.Close()
con.Close()

Using...End Using blocks ensure that your database objects are closed and disposed. You can use .ExecuteScalar to get a single value from the database. This returns an Object so a CInt is needed. I think one of your problems was that you were surrounding MV in single quotes in the second Select statement. I am sure that this is an Integer and you were passing it as a string. Using parameters solves this problem.
Private Sub president()
Using con As New MySqlConnection(ConStr),
cmd1 As New MySqlCommand("SELECT MAX(VOTECOUNT) as MV FROM candidates WHERE POSITION = 'PRESIDENT'", con)
con.Open()
Dim MV = CInt(cmd1.ExecuteScalar())
cmd1.CommandText = "SELECT CONCAT(FIRSTNAME,' ',MIDDLENAME,' ',LASTNAME) AS FULLNAME,POSITION, VOTECOUNT FROM candidates WHERE POSITION = 'PRESIDENT' AND VOTECOUNT = #MV"
cmd1.Parameters.Add("#MV", MySqlDbType.Int32).Value = MV
Using rd = cmd1.ExecuteReader()
While rd.Read()
TextBox1.AppendText(rd("FULLNAME").ToString & vbCrLf)
End While
End Using
End Using
End Sub

Related

how to count all rows within the tables on a database then display in a textbox? [duplicate]

There are 10 rows in primary_student_table.
When I execute the following code, the result was -1.
Dim count As Int16
con.Open()
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 "
cmd = New SqlCommand(query, con)
count = cmd.ExecuteNonQuery
MsgBox(count)
con.Close()
What's the problem in the above code?
You should be using ExecuteScalar() rather than ExecuteNonQuery() because you are fetching a value.
count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
SqlCommand.ExecuteScalar Method
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exceptions
Example Code:
Dim connStr As String = "connection string here"
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Try
conn.Open()
Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
Catch(ex As SqlException)
' put your exception here '
End Try
End Using
End Using
The solution is to replace
count = cmd.ExecuteNonQuery
with
count = cmd.ExecuteScalar
Like Robert Beaubien said in his comments
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "Select * from dblms.accounts"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
the value in count will be the number of rows in a table :) hope this helped

Visual Basic and Mysql in phpMyadmin [duplicate]

I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.

How can I solve this cross thread error?

Cross-thread operation not valid: Control textbox accessed from a thread other than the thread it was created on. vb.net
Sub autocompletepayee()
Dim cmd2 As New Odbc.OdbcCommand
Dim dr As Odbc.OdbcDataReader
Dim myquery As String
myquery = "select payee from tbrequest"
cmd2.CommandText = myquery
cmd2.Connection = con
dr = cmd2.ExecuteReader
While dr.Read
txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt
End While
dr.Close()
This should work, though it might be shorter if more were known about where the code was located
Dim cmd2 As New Odbc.OdbcCommand
Dim dr As Odbc.OdbcDataReader
Dim myquery As String
myquery = "select payee from tbrequest"
cmd2.CommandText = myquery
cmd2.Connection = con
dr = cmd2.ExecuteReader
While dr.Read
If txtPayee.InvokeRequired Then
txtPayee.Invoke(Sub()
txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt
End Sub)
Else
txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt
End If
End While
dr.Close()

Converting mysql query to be used in vb.net

I am newbie in mysql and vb.net and have this query:
select `db_employee`.`firstName` as `firstName`, `db_employee`.`lastName` as `lastName`,
`tbl_employment`.`position` as `position`
from (`db_employee` `db_employee`
inner join `tbl_employment` `tbl_employment` on (`tbl_employment`.`ctrlID` = `db_employee`.`ctrlID`))
where (`tbl_employment`.`companyName` like 'MES%')
And I want to convert it to be used here:
Dim MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = connStr
Dim SDA As New MySqlDataAdapter
Dim dbdataset As New DataTable
Dim bsource As New BindingSource
MySqlConn.Open()
Dim query As String
query = ?
you can use below code for displaying data... i hope this what you want.. :)
Dim cn As SqlConn= New SqlConn("Connecting String")
Dim cmd As sqlCommand
Dim dr As sqlDataReader
cn.open()
cmd = New sqlCommand("select * from table or your query, cn)
dr = cmd.ExecuteReader()
dr.Read()
textbox1.Text = dr(1).ToString()
cn.close()
You can do something like this with the MySQL provider you're using. This will create your connection, command and data reader and close and dispose of everything properly. If you want a DataTable instance, you can load it from the DataReader.
Using conn As New MySql.Data.MySqlClient.MySqlConnection("YourConnectionString")
conn.Open()
Using cmd As MySql.Data.MySqlClient.MySqlCommand = conn.CreateCommand
cmd.CommandText = "select db_employee.firstName as firstName, " & _
"db_employee.lastName as lastName, " & _
"tbl_employment.position as position " & _
"from db_employee db_employee " & _
"inner join tbl_employment tbl_employment on tbl_employment.ctrlID = db_employee.ctrlID " & _
"where tbl_employment.companyName like 'MES%' "
' Get a data reader that you can loop over or load a data table with
Dim dr As MySql.Data.MySqlClient.MySqlDataReader = cmd.ExecuteReader
' How to read with a DataReader
While dr.Read
' Do something with this
Dim lastName As String = dr("lastName")
End While
End Using
conn.Close()
End Using

How to use if condition using two tables in MySQL

Can anyone help me on this? What I wanted to happen is that if the value exist in Table 1 (employee), it will then check Table 2 (mobilelist) if it also exist there. Here's the code:
Private Sub TextBox_IDNumber_LostFocus(sender As Object, e As EventArgs) Handles TextBox_IDNumber.LostFocus
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;password=12345;database=my_db"
Dim READER As MySqlDataReader
Dim READER2 As MySqlDataReader
Dim _isFound As Boolean = False
Dim _isExist As Boolean = False
Try
Mysqlconn.Open()
Dim empmr As String
Dim empml As String
Dim fn1 As String
Dim fn2 As String
Dim ln1 As String
Dim ln2 As String
empmr = "Select * from my_db.employee where IDNumber ='" & TextBox_IDNumber.Text & "'"
empml = "Select * from my_db.mobilelist where IDNumber = '" & TextBox_IDNumber.Text & "' AND DateAssigned is not Null AND DateReturned is Null"
Command = New MySqlCommand(empmr, Mysqlconn)
READER = Command.ExecuteReader
While READER.Read()
_isFound = True
fn1 = READER.GetString("FirstName")
ln1 = READER.GetString("LastName")
End While
If _isFound Then
TextBox_FirstName.Text = fn1
TextBox_LastName.Text = ln1
ElseIf Not _isExist Then
MessageBox.Show("Record Not Found in Master Data")
TextBox_IDNumber.Clear()
TextBox_FirstName.Clear()
TextBox_LastName.Clear()
TextBox_IDNumber.Focus()
End If
Catch ex As MySqlException
MessageBox.Show("Error!")
Finally
Mysqlconn.Dispose()
End Try
End Sub
Assuming you have the appropriate Primary Key and Foreign Key relationship between the tables Employee and MobileList you use this query to find records on the MobileList table for an employee:
Dim myQuery as string
myQuery = "SELECT FirstName, LastName, MobileNumber
FROM Employee
JOIN MobileList
ON Employee.IDNumber=MobileList.IDNumber
WHERE Employee.IDNumber=#ID"
Note: You should rename the IDNumber column on the MobileList to avoid confusion.
You should also improve your access to the database with the Using statement and take advantage of Parameters to prevent SQL injection:
Using myConn As New SqlConnection("Your connection string")
myConn.Open()
Using myCmd As New SqlCommand(myQuery, myConn)
myCmd.Parameters.AddWithValue("#ID", "Your ID value")
Using myReader As SqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows Then
'There are mobile numbers issued to that ID'
Do While myReader.Read()
'Iterate through all existing records'
Loop
Else
'There are no mobile numbers issued to that ID'
End If
End Using
End Using
End Using
Keep in mind that this gives you the mobile numbers for a particular employee, it doesn't tell you if a particular employee exists.