I'm looking for code that will help me check a particular column in MySQL and return its value if it already exists.
I'm working on ForgotPassword module, so when the user clicks "Forgot Password", a form appears that will ask the user to input his/her username. Once he's/she's done, it will check the system to see if the entered username exists.
I found some code here on Stack Overflow:
Private Sub btnCheckUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUser.Click
If IsUserExist(userName:=True) Then
MsgBox("user exists")
Else
MsgBox("user does not exists")
End If
End Sub
Private Function IsUserExist(ByVal userName As String) As Boolean
Dim query As String
Dim returnValue As Boolean = False
query = "SELECT username FROM dbase.tblusers WHERE username = #username "
Using conn As New MySqlConnection("server=localhost; userid=root; password=root; database=dbase")
Using cmd As New MySqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#username", txtUsername.Text)
End With
Try
conn.Open()
If CInt(cmd.ExecuteScalar()) > 0 Then
returnValue = True
End If
Catch ex As MySqlException
MsgBox(ex.Message)
returnValue = False
Finally
conn.Close()
End Try
End Using
End Using
Return returnValue
End Function
But this code gives me an error Conversion from string "username" to type 'Integer' is not valid at If CInt(cmd.ExecuteScalar()) > 0 Then.
MySqlCommand.ExecuteScalar returns the first column of the first row returned by your query. This means (for your actual query) a NULL (if the username doesn't exist) or a string with the same username passed as parameter for the where condition. In any case not an integer.
So you just need to check if the object returned is null(Nothing in VB.NET).
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing then
... user exists....
Another approach at your problem could be getting back a COUNT of the number of rows that contains your username
query = "SELECT COUNT(*) FROM dbase.tblusers WHERE username = #username"
and then, the conversion to an integer of the return value of ExecuteScalar, will work
Finally, about the syntax If IsUserExist(userName:=True) Then.
This probably works just because you have the Option Strict configuration of your project set to Off.
With this configuration the boolean value True is automatically converted in the datatype expected by the parameter in IsUserExist. So this function receives the parameter username equals to the literal string "True". Not really useful when you try to search some real username in your table.
It seems that you need to get that value somewhere in your buttonclick code, probably from a TextBox.
Private Sub btnCheckUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUser.Click
Dim userName = txtUsername.Text
If IsUserExist(userName) Then
MsgBox("user exists")
Else
MsgBox("user does not exists")
End If
End Sub
Of course, now you should use the variable userName received in IsUserExist to intialize the parameter
With cmd
.Parameters.AddWithValue("#username", userName)
....
Private Sub btnCheckUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUser.Click
If IsUserExist(txtUsername.Text) Then #Use value from textbox on your form, use '#' for comments
MsgBox("user exists")
Else
MsgBox("user does not exists")
End If
End Sub
Private Function IsUserExist(ByVal userName As String) As Boolean
Dim query As String
Dim returnValue As Boolean = False
query = "SELECT username FROM dbase.tblusers WHERE username = #username "
Using conn As New MySqlConnection("server=localhost; userid=root; password=root; database=dbase")
Using cmd As New MySqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#username", userName) # I think here should user value from function's parameter, not from textbox
End With
Try
conn.Open()
If CInt(cmd.ExecuteScalar()) > 0 Then
returnValue = True
End If
Catch ex As MySqlException
MsgBox(ex.Message)
returnValue = False
Finally
conn.Close()
End Try
End Using
End Using
Return returnValue
End Function
Related
I am trying to display value in combobox using MySQL in vb.net. Right now the problem that I am facing is that combobox is not displaying values from MySQL. I have the below code:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
However, using the above code Combobox1.Text returns nothing but if I use below code which has a different query it works:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("Name")
ComboBox1.Items.Add(sName)
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Could someone please check and let me know what could be the issue? Thanks!
so the highlights as i mentioned them in the comments
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' You need only to open aconnection once
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "db connection successful"
'First load both Combobox
Dim query As String
query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sname = READER.GetString("name")
ComboBox1.Items.Add(sname)
ComboBox2.Items.Add(sname)
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Closing
Try
MySqlConn.Close()
MySqlConn.Dispose()
Catch ex As Exception
End Try
End Sub
ANd now the Comboboxes
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'Only when there is a item selected , ask for data
If ComboBox1.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label11.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
This is exactly as i described on Form_load you fill both comboboxes
When you now change one of the comboxes one of the label change too.
Sometimes you have to update the Element to see a change
in that case you write at the end of the loop
Label10.Update()
Starting at the top...
Keep your database objects local to the method where they are used. (Not Form level variables) You can make the connection string a class level string variable. This is the only way you can ensure that they are closed and disposed.
Using...End Using blocks will close and dispose your database objects even if there is an error. The constructor of the connection takes the connection string. Connections are precious objects. Don't open the connection until directly before the .Execute method and close it as soon as possible.
It doesn't make much sense that the user could select an item from ComboBox1 before the Form.Load.
In general, we don't want to download anymore data than necessary and we want to hit the database as little as possible. In the Form.Load we bind the combobox to a data table that contains the name and price fields, setting the display and value members. Now, whenever the user picks a name in the combo we can retrieve the price without connecting to the database again.
I noticed that you were using Val in another event. This is an old VB6 method that can give you unexpected results. .Net and vb.net have all sorts of ways to get numbers out of strings that are faster and more reliable. CInt, .TryParse, .Parse, CType, Convert.To etc.
Public Class Form1
Private ConString As String = "server=localhost;userid=root;password=root;database=s974_db"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Fill combobox
Dim dt As New DataTable
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("select Name, Price from processors;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using 'Closes and disposes both connection and command
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Price"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Label10.Text = ComboBox1.SelectedValue.ToString
ClearLabels()
End Sub
Private Sub ClearLabels()
Label11.Text = ""
Label12.Text = ""
Label13.Text = ""
Label14.Text = ""
Label15.Text = ""
Label16.Text = ""
Label17.Text = ""
Label18.Text = ""
Label19.Text = ""
Label20.Text = ""
End Sub
End Class
i'm using vb 2017. I try to save combobox value and checkedlistbox item into database. The database table only shows "System.Data.DataRowView" for combobox and "System.Windows.Forms.CheckedListBox+ObjectCollection" for checkedlistbox. Can anyone help me? I'm using mysql phpmyadmin for database. This is the codes i'm using below. it show no error. But the selected item value has not show in database table.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "server=localhost;user=root;database=login;port=3306;password=root123;SslMode=none"
Dim conn As MySqlConnection = New MySqlConnection(constr)
Dim result As Integer
'If True Then
Try
conn.Open()
With {}
Dim cmd As MySqlCommand
For Each item In CheckedListBox1.CheckedItems
cmd = New MySqlCommand("INSERT INTO mastersubject(name,subjectpriority) VALUES(#name,#subjectpriority)", conn)
Next
cmd.Parameters.AddWithValue("#name", ComboBox1.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#subjectpriority", CheckedListBox1.Items.ToString())
result = cmd.ExecuteNonQuery()
'conn.Close()
End With
'End If
If result > 0 Then
MsgBox("Record has been saved")
Else
MsgBox("Error!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
Catch ex As Exception
Console.WriteLine(ex.ToString())
MsgBox(ex.Message)
Finally
conn.Close()
End Try
End Sub
Comments and Explanations are in line.
Private Sub InsertRecord()
Dim constr As String = "server=localhost;user=root;database=login;port=3306;password=root123;SslMode=none"
'A Using...End Using block will ensure that your data objects
'are closed and disposed event if there is an error
Try
Using conn As MySqlConnection = New MySqlConnection(constr)
'You need the new keyword to create the command
'Pass the sql query string and the connection object to the
'constructor of the command
'Create the command once, only the value of the subjectpriority changes
Using cmd As New MySqlCommand("INSERT INTO mastersubject (name, subjectpriority) VALUES (#name, #subjectpriority);", conn)
cmd.Parameters.AddWithValue("#name", ComboBox1.SelectedItem.ToString)
cmd.Parameters.Add("#subjectpriority")
'Open the connection as late as possible
conn.Open()
For i = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim Result As Integer
'You are not adding a new parameter, just changing its value
cmd.Parameters("#subjecpriority").Value = CheckedListBox1.CheckedItems(i).ToString()
'the command will be executed for each item checked
Result = cmd.ExecuteNonQuery()
If Result > 0 Then
MessageBox.Show("Record has been saved")
Else
MessageBox.Show("Error!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
Next
End Using 'Disposes the command
End Using ' closes and disposes the connection
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
This the code that I use. The message box is appearing but when I select yes, the selected row is not deleted at the datagridview and database.
Private Sub Delete2_Click_1(sender As Object, e As EventArgs) Handles Delete2.Click
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=127.0.0.1;userid=root;password=;database=equipment"
Try
If Me.DataGridView2.Rows.Count > 0 Then
If Me.DataGridView2.SelectedRows.Count > 0 Then
Dim intStdID As Char = Me.DataGridView2.SelectedRows(0).Cells("asset_code").Value
'open connection
If Not MySqlConn.State = ConnectionState.Open Then
MySqlConn.Open()
End If
'delete data
Dim cmd As New MySqlCommand
cmd.Connection = MySqlConn
cmd.CommandText = "DELETE * FROM equipment.equipment" & intStdID
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = Windows.Forms.DialogResult.Yes Then
cmd.ExecuteNonQuery()
Else : Exit Sub
End If
'refresh data
Load_table()
'close connection
MySqlConn.Close()
End If
End If
Catch ex As MySqlException
End Try
Look at this line:
cmd.CommandText = "DELETE * FROM equipment.equipment" & intStdID
It attempts to append the ID value from the selected cell to the SQL statement. However, it seems like this is just the ID value. You also need the WHERE ID= portion for the query.
Moreover, it's using this ID value in the query in the wrong way. It's NEVER okay to use string concatenation to include data in a query. You must use parameterized queries.
The code below demonstrates this, as well as several other better patterns for this method, with the caveat that I had to guess as some names and types from your database.
Private Sub Delete2_Click_1(sender As Object, e As EventArgs) Handles Delete2.Click
If Me.DataGridView2.Rows.Count = 0 OrElse Me.DataGridView2.SelectedRows.Count = 0 Then
Exit Sub
End If
Dim res As DialogResult = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res <> DialogResult.Yes Then Exit Sub
Dim intStdID As Char = Me.DataGridView2.SelectedRows(0).Cells("asset_code").Value
Dim SQL as String = "DELETE * FROM equipment.equipment WHERE equipment.StdID= #AssetCode"
Using con As New MySqlConnection("server=127.0.0.1;userid=root;password=;database=equipment"), _
cmd As New MySqlCommand(SQL, con)
cmd.Parameters.Add("#AssetCode", MySqlDbType.VarChar, 1).Value = intStdID
con.Open()
cmd.ExecuteNonQuery()
End Using
Load_table()
End Sub
I don't know what's the real problem since there are no error being reported. So what I want these codes to do is insert a transaction record to the database but there is nothing being returned. Here are the codes that related to this:
MainForm
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim payment As New Payment
payment.Show()
AddHandler payment.PaymentEvent, AddressOf paymentSuccess
payment.PaymentAmount = TransactionTotal
End Sub
Public Sub paymentSuccess(ByVal sender As Object, ByVal e As Payment.PaymentMadeEventArgs)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "select * from inventory"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
Dim itId As Integer = reader.GetString("itemid")
Dim itName As String = reader.GetString("itemname")
If e.PaymentSuccess = True Then
paymentSuccessQuery(itId, itName)
End If
End While
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) VALUES('" & itemid & "', '" & itemname & "')"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
If reader.Read Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Transactionform
Public Class Payment
Public Delegate Sub PaymentMadeEvent(ByVal sender As Object, ByVal e As PaymentMadeEventArgs)
Public Event PaymentEvent As PaymentMadeEvent
Private _paymentAmount As Decimal
Public Property PaymentAmount As Decimal
Get
Return _paymentAmount
End Get
Set(ByVal value As Decimal)
_paymentAmount = value
AmountBox.Text = String.Format("{0:c}", _paymentAmount)
End Set
End Property
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim total As Decimal = 0
Try
total = Decimal.Parse(AmountBox.Text.TrimStart("₱")) - Decimal.Parse(PaymentBox.Text)
Catch
MessageBox.Show("Error Occured, please enter a valid amount!")
Return
End Try
If (total > 0) Then
AmountBox.Text = total.ToString()
Else
MessageBox.Show("Please give " + String.Format("{0:c}", -total))
RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() With {.PaymentSuccess = True})
End If
End Sub
Public Class PaymentMadeEventArgs
Inherits EventArgs
Private _paymentSuccess As Boolean
Public Property PaymentSuccess As Boolean
Get
Return _paymentSuccess
End Get
Set(ByVal value As Boolean)
_paymentSuccess = value
End Set
End Property
End Class
End Class
ExecuteReader executes the command (the insert) but it has been built to return the rows extracted by a SELECT command.
Calling Read to discover if your INSERT has been successful is meaningless in this context.
You should call ExecuteNonQuery, catch the return value, and if it is not equal to zero, then you have inserted the record.
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
Using mydbcon = New MySqlConnection("server=localhost;userid=root;password=;database=sdudb"
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) " & _
"VALUES(#id, #name)"
Using COMMAND = New MySqlCommand(Query, mydbcon)
COMMAND.Parameters.Add("#id", MySqlDbType.VarChar).Value = itemid
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = itemname
Dim rowsAdded = COMMAND.ExecuteNonQuery()
if rowsAdded = 0 Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Notice also the I have changed your code to use the appropriate Using statement around the disposable objects like the connection and the command and, of utmost importante, I have changed your query to use a more safe parameterized query approach (not sure about the MySqlDbType for the ID parameter, it seems to be an integer but in your original query you put it between single quotes like a string)
i have a code but it's not working. i was trying to put a value in label2 but it's not working. please help me.
Private Sub student_no_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles student_no.Click
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = sample;"
Dim READER As MySqlDataReader
Try
MySqlConnection.Open()
Dim query As String
query = " select id from sample.student where last_name = '" & txtlastname.Text & "' "
Dim Command As New MySqlCommand(query, MySqlConnection)
READER = Command.ExecuteReader
Label2.Text = query.ToString
MessageBox.Show("Student Number Generated")
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
You are using .ToString on query, which is a string. What you should be doing is operations on the READER object.
Since SELECT will always return a list of results, you have to treat the results as such, like...
While READER.Read()
MessageBox.Show((READER.GetInt32(0)))
End While
.Read() returns the next element in the returned rowset
If READER.Read() Then
Label2.Text = READER.GetString(0)
End If