How to get UPDATE SQL commands working in VB.net and MySQL? - vb.net

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost; username=root; password=; database=wh_db")
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
con.Open()
cmd.Connection = con
cmd.CommandText = " select pass from user where pass ='" & oldpass.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
cmd.Connection = con
cmd.CommandText = " UPDATE user SET pass ='" & newpass.Text & "' where user = '" & user.Text & "'"
Else
MsgBox("Password is not correct")
End If
End Sub

I've not used MySQL for a while but have a look at this. It should give you some start into what you're after:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dr As MySqlDataReader
Using con As New MySqlConnection(yourConnectionString),
cmd As New MySQLCommand("SELECT pass FROM user WHERE pass = #pass", con)
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = oldpass.Text
con.open()
dr = cmd.ExecuteReader
End Using
If dr.HasRows Then
Using con As New MySqlConnection(yourConnectionString),
cmd As New MySQLCommand("UPDATE user SET pass = #pass WHERE user = #user", con)
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = newpass.Text
cmd.Parameters.Add("#user", MySqlDbType.VarChar).Value = user.Text
con.open()
cmd.ExecuteNonQuery()
End Using
Else
MsgBox("Password is not correct")
End If
End Sub
The reason you're not updating is because you haven't told the command to update. I've also implemented Using which I suggest you do and also look at parameters to stop SQL injection.
I've separated both statements into two Using statements as I feel this would be better rather than attempting to reuse the same object for both the SELECT and UPDATE command.

Related

Oledb No Value Given for one or more required parameters VB.NET

I can anyone tell me whats wrong with my code? I am a complete novice here and this is the first time I have tried writing something in quite a while,
The below code should be updating two fields in an access database
Private Sub TestButton_Click(sender As Object, e As EventArgs) Handles TestButton.Click
'connects application to database
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DatabasePath\database.accdb"
Dim SqlString As String = "update SaintStaff set [StaffHours]=[#CAHours],[RecordedTime]=[#Time] where [StaffName] = " & Label2.Text & ""
'updates record in SaintStaff table.
Using conn As New OleDbConnection(ConnString)
conn.Open()
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("[#CAHours]", Label6.Text)
cmd.Parameters.AddWithValue("[#Time]", Label10.Text)
cmd.ExecuteNonQuery()
End Using
conn.Close()
End Using
End Sub
I am getting the following error
System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
and its highlighting the cmd text on each line, I cant tell what I am doing wrong, can anyone help?
Thank you
This Question was answered by MatSnow and olivier-jacot-descombes in the comments, the correct code looks as follows
Private Sub TestButton_Click(sender As Object, e As EventArgs) Handles TestButton.Click
'connects application to database
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DatabasePath\Database.accdb"
Dim SqlString As String = "update SaintStaff set StaffHours = #CAHours, RecordedTime = #Time where StaffName = #staffname "
'updates record in SaintStaff table.
Using conn As New OleDbConnection(ConnString)
conn.Open()
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CAHours", OleDbType.VarChar).Value = Label6.Text
cmd.Parameters.Add("#Time", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#Staffname", OleDbType.VarChar).Value = Label2.Text
cmd.ExecuteNonQuery()
End Using
conn.Close()
End Using
End Sub

syntax error in false clause and when I search for names nothing displays

One time when I run this code it run smoothly but then when i search for names there is no record appears. Badly need your help guys for our program project. thanks in advance :)
This is my code :
Private Sub search_btn_Click(sender As Object, e As EventArgs) Handles search_btn.Click
Me.Show()
Search_Record()
End Sub
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\VB\HSU\HSU\G11B.mdb"
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT Last_Name, First_Name FROM 10ABM"
sSQL = sSQL & "WHERE Last_Name like '%" & Me.search_txt.Text & "%'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub

Data source name not found and no default driver specifie

Help i am using vb.net2010 and trying to access my database through sqlyog but there seems to be an error on con.Open() line.(I'm trying to create a login form with a database and this is my first time)
Public con As New Odbc.OdbcConnection
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
con = New Odbc.OdbcConnection("dsn=cara")
Dim cmd As New Odbc.OdbcCommand
Dim reader As Odbc.OdbcDataReader
cmd.Connection = con
con.Open()
cmd.CommandText = " SELECT username,password FROM userinfo WHERE username='" & txtusername.Text & "' and password='" & txtpassword.Text & "'"
reader = cmd.ExecuteReader
If reader.HasRows Then
Admin_Page.Show()
Else
MessageBox.Show("Invalid Username or Password")
End If

The connection string property has not been initialized

I am trying to search my database using the below code, but I am getting the above error.
Private Sub ButtonSearch_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSearch.Click
myConnection.Open()
Textlocation.Clear()
Dim str As String
str = "select * From STUDENTS where ADMINNO like " & "'%" & SearchTextBox.Text & "%'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
Textadminac.Text = dr("ADMINNO").ToString
End While
myConnection.Close()
End Sub

error show on There is already an open DataReader associated with this Command which must be closed first

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer = 0
str = "select Vote from vote where party='Green'"
cmd = New SqlCommand(str, con)
con.Open()
dr = cmd.ExecuteReader()
if dr.HasRows Then
dr.Read()
n = dr("Vote").ToString()
n = n + 1
Label8.Text = n.ToString()
End If
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
dr.Read()
cmd.Dispose()
con.Close()
End Sub
The message seems to be pretty clear. You have to close the DataReader before trying to use the connection for another operation
MSDN says
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
....
dr.Close()
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
' ??? dr.Read()
cmd.Dispose()
con.Close()
By the way, your whole code could be simplified using an ExecuteScalar to retrieve the last vote value and dumping the DataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer = 0
str = "select Vote from vote where party='Green'"
Using cmd = New SqlCommand(str, con)
con.Open()
Dim n as Integer
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
n = Convert.ToInt32(result) + 1
else
n = 1
End If
Label8.Text = n.ToString()
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd.CommandText = str
cmd.ExecuteNonQuery()
con.Close()
End Using
End Sub
In this scenario you use a global connection object and this should be avoided. Remember that it is always better to create, open, use and destroy the connection when you need to use it. SqlClient classes could use the Connection Pooling infrastructure that could help a lot in managing precious resources like a connection
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
try
Dim n As Integer = 0
str = "select Vote from vote where party='Green'"
cmd = New SqlCommand(str, con)
con.Open()
dr.Close()
dr = cmd.ExecuteReader()
if dr.HasRows Then
dr.Read()
n = dr("Vote").ToString()
n = n + 1
Label8.Text = n.ToString()
End If
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
dr.Read()
Finally
cmd.Dispose()
con.Close()
End Try
End Sub
Add multiple active results set to your connection string as shown below
Example:
"Server=Server;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true;"