I want update mysql database table in vb.net, i try and i got problem with that. this is my source
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=db4free.net;port=3306;userid=***;password=***;database=***"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "update member set (Name='" & Val(TextBox1.Text) + Val(TextBox6.Text) & "' WHERE Username='" & TextBox8.Text & "'"
Command = New MySqlCommand(Query, MysqlConn)
Reader = Command.ExecuteReader
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
If i do this source, i got error code like this
TextBox1.Text = 10
TextBox6.Text = 20
TextBox8.Text = John
Here's what you have
"update member set (Name='" & Val(TextBox1.Text) + Val(TextBox6.Text) & "' WHERE Username='" & TextBox8.Text & "'"
render:
update member set (Name='30' WHERE Username='John'
-
What you probably want is to remove the bracket
"update member set Name='" & Val(TextBox1.Text) + Val(TextBox6.Text) & "' WHERE Username='" & TextBox8.Text & "'"
resulting in :
update member set Name='30' WHERE Username='John'
My suggestion to you as a preference for building these strings is to separate the parameters more often. It keeps things neat and easy.
ex:
dim x as string = (Val(TextBox1.Text) + Val(TextBox6.Text)).tostring
dim cmd as string =
"update member " &
"set Name=" & "'" & x & "' " &
"WHERE Username=" & "'" & TextBox8.Text & "'"
Related
here my query if anyone can spot error
str = "update student set course='" & ComboBox1.Text & "',name='" &
TextBox2.Text & "',f_name='" & TextBox3.Text & "',address='" & TextBox4.Text
& "' ,tel_no='" & TextBox5.Text & "',qualification='" & TextBox6.Text &
"',remarks='" & TextBox7.Text & "',school/college='" & TextBox8.Text &
"',fee='" & TextBox10.Text & "' where reg_no=" & TextBox9.Text & " "
Here is a better way to build this query:
str = "update student " &
" set course= #course, name= #name, f_name= #fname, address= #address," &
" tel_no= #tel, qualification = #qualification, remarks= #remarks," &
" `school/college`=#school, fee= #fee" &
" where reg_no= #regno"
Using cn As New MySqlConnection("connection string here"), _
cmd As New MySqlCommand(str, cn)
'Use actual column types/lengths from your DB here
cmd.Parameters.Add("#course", MySqlDbType.VarChar, 15).Value = ComboBox1.Text
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 25).Value = TextBox2.Text
cmd.Parameters.Add("#fname", MySqlDbtype.VarChar, 25).Value = TextBox3.Text
cmd.Parameters.Add("#address", MySqlDbType.VarChar, 120).Value = TextBox4.Text
cmd.Parameters.Add("#tel", MySqlDbType.VarChar, 25).Value = TextBox5.Text
cmd.Parameters.Add("#qualification", MySqlDbType.VarChar, 40).Value = TextBox6.Text
cmd.Parameters.Add("#remarks", MySqlDbType.VarString).Value = TextBox7.Text
cmd.Parameters.Add("#school", MySqlDbType.VarChar, 40).Value = TextBox8.Text
cmd.Parameters.Add("#fee", MySqlDbType.Decimal, 6, 2).Value = Convert.ToDecimal(TextBox10.Text)
cmd.Parameters.Add("#regno", MySqlDbType.Int32).Value = Integer.Parse(TextBox9.Text)
cn.Open()
cmd.ExecuteNonQuery()
End Using
This does a number of things for you:
It prevents sql injection attacks
It allows you to accept data that includes things like single quotes ('). The code you have will fail if someone puts in a single quote.
It handles things like date formatting for the sql automatically.
It's faster, because the database server can cache the execution plan after it compiles the query, and use statistics over time to get better execution plans.
It closes the db connection more reliably. The current code leaves the database connection hanging open if an exception is thrown.
i have tried this code here to insert and show picture from database to picturebox : stackoverflow.com/questions/5624760/store-picture-to-database-retrieve-from-db-into-picturebox
and yeah, it is working , but when i tried to do update using the same syntax as insert it got this error :
this is the insert syntax i use :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "insert into tbmahasiswa VALUES ('" & _
txtNIM.Text & "','" & _
txtNama.Text & "','" & _
Format(dtpTanggal.Value, "yyyy-MM-dd") & "','" & _
txtAlamat.Text & "','" & _
cboJurusan.Text & "',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and this the code i use to show picture from database to picture box :
Dim imgData As Byte()
call konek
strSQL = "select * from tbMahasiswa where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNama.Text = rd.Item(1)
dtpTanggal.Value = rd.Item(2)
txtAlamat.Text = rd.Item(3)
imgData = TryCast(rd.Item(5), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
Both Insert and Retrieving Picture Code above is Working ! , and then i use this code for update :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "update tbmahasiswa set Nama ='" & txtNama.Text & _
"', TglLahir ='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"', Alamat ='" & txtAlamat.Text & _
"', Jurusan ='" & cboJurusan.Text & _
"', gambar =' #gambar" & _
"' where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and then i got the error like in the picture above, all other data is correctly saved except the picture, it become some unknown file blob 8 KB size.
i'm still newbie at insert , update, delete picture in VB, please can you tell me what is wrong with the Update syntax code , is it already true but i'm missing something ? or is it totally wrong with the syntax ? please i need your guide here...
UPDATE :
actually there is "call konek" above "STRSQL" in the code, "konek" have the code for open the mysql connection,i put it in the separate module, here the full code in my module :
Module modKoneksi
Public conn As New MySql.Data.MySqlClient.MySqlConnection
Public rd As MySql.Data.MySqlClient.MySqlDataReader
Public com As MySql.Data.MySqlClient.MySqlCommand
Public strSQL As String
Public Sub konek()
conn.Close()
strSQL = "server='localhost';user='root';pwd='';database='dbsekolah';"
Try
conn.ConnectionString = strSQL
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End
End Try
End Sub
End Module
hope this makes you easier to solve my problem
I know its late but this is the working code for me :
For retrieving the record from database with pictures :
Call konek() 'Call the connection module'
strSQL = "select * from tbMahasiswa where ID ='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNIM.Text = rd.Item(1)
txtNama.Text = rd.Item(2)
dtpTanggal.Value = rd.Item(3)
txtAlamat.Text = rd.Item(4)
imgData = TryCast(rd.Item(6), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
cboJurusan.SelectedIndex = cboJurusan.FindStringExact(rd.Item(5))
End If
End Using
For inserting record to database with pictures :
Call konek()
strSQL = "Insert Into tbmahasiswa Values ('" & txtID.Text & _
"','" & txtNIM.Text & _
"','" & txtNama.Text & _
"','" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"','" & txtAlamat.Text & _
"','" & cboJurusan.Text & _
"',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then 'opdGambar is a PictureBox name'
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes("man-icon.png") 'Insert field gambar using an existing file in debug folder if file does not exist in PictureBox'
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName) 'Insert field gambar using an existing file in PictureBox'
End If
com.ExecuteNonQuery()
End With
For updating record to database with pictures :
Call konek()
Dim adapter As New MySql.Data.MySqlClient.MySqlDataAdapter("select gambar from tbmahasiswa where ID='" & txtID.Text & "'", conn)
Dim dt As New DataTable("gambar")
adapter.Fill(dt)
strSQL = "update tbmahasiswa set NIM='" & txtNIM.Text & _
"',Nama='" & txtNama.Text & _
"',TglLahir='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"',Alamat='" & txtAlamat.Text & _
"',Jurusan='" & cboJurusan.Text & _
"' ,Gambar=#gambar where id='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row(0), Byte()))
Dim img As Image = Image.FromStream(ms)
gambar.Image = img
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = (CType(row(0), Byte())) 'field gambar will use the current existing file in database if PictureBox does not have a file'
End Using
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName)
End If
com.ExecuteNonQuery()
End With
i hope for those who find the other answer a little confusing (like me), will find this answer helpful.
I'm despairing because an mysql error is in my code and I didn't find any helpful answer.
Code:
cn.ConnectionString = "Server=" & host.Text & ";User Id=" & user.Text & ";Password=" & password.Text & ";Database=" & database.Text & ";"
cmd.Connection = cn
Try
cn.Open()
cmd.CommandText = "LOAD DATA LOCAL INFILE '" & directory.Text & "' INTO TABLE " & database.Text & "." & table.Text & ";"
MsgBox(cmd.CommandText)
dr = cmd.ExecuteReader
Catch exError As MySqlException
MsgBox("Error: " & exError.Message, MsgBoxStyle.Critical)
End Try
cn.Close()
Screenshot of the error:
http://i.imgur.com/gkEsspQ.png
Edit: Screenshot 2 of the error (more detailed): http://i.imgur.com/iyOsAxr.png
When I use this line:
cmd.CommandText = "LOAD DATA LOCAL INFILE 'D:/Bibliothek/Desktop/test.txt' INTO TABLE test.test;
it works.
I think this is the problem.
When you use VB.Net values in MySQL query Remember to start like this '" and end like this "'
'" textbox1.text "'
When I run this function
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim command As MySqlCommand = New MySqlCommand
Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
Dim reader As MySqlDataReader
SQLConnection.Open()
command.CommandText = sqlQuery
command.Connection = SQLConnection
reader = command.ExecuteReader
SQLConnection.Close()
Catch excep As Exception
MsgBox(excep.ToString)
End Try
Next
in my program I get an error saying "The connection property has not been set or is null"
How can I get rid of this?
It goes to the exception when it gets to SQLconnection.Open()
I created the ServerString and MySQL connection at the top of the module like so:
Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection
You are opening a connection without its property
It should be,
Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open
Also, you may want to use the USING function so that your connection is properly closed.
It seems you are just inserting a bunch of values to your database and not retrieving anything so why do you use a DataReader?
Your code should be something like this:
Using SQLConnection = New MySqlConnection(ServerString)
SQLConnection.Open 'You should open a connection only once
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim sqlQuery As String = "INSERT INTO bookings SET " & _
"Date='" & strDateToBook & "'," & _
"RoomID='" & strComputerRoomToBook & "', " & _
"Length='" & intNewBookingLength & "', " & _
"Period='" & intNewStartPeriod & "', " & _
"UserID='" & intid & "'"
Dim command = New MySqlCommand(sqlQuery, SQLConnection)
command.ExecuteNonQuery
Catch excep As Exception
MsgBox(excep.Message)
End Try
Next
End Using
Also, you may want to change how to pass your values into a parameter. This will prevent SQL Injection.
Good evening all,
I'm using the following as an attempt to update records in my MySQL database, but the records aren't being updated and I'm not catching any exceptions either. Your help would be kindly appreciated:
dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=trojan;Password=horse;Database=accounting")
Try
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
Else
Try
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("UPDATE customer " & _
"SET accountNumber= '" & TextBoxAccount.Text & "', nameLAST='" & TextBoxLastName.Text & "', nameFIRST='" & TextBoxFirstName.Text & "'" & _
"nameSALUTATION='" & ComboBoxSalutation.SelectedItem & "', nameCOMPANY='" & TextBoxCompanyName.Text & "', addressSTREET='" & TextBoxAddress1.Text & "'" & _
"addressSTREET1='" & TextBoxAddress2.Text & "', addressCITY='" & TextBoxCity.Text & "', addressSTATE='" & ComboBoxState.SelectedItem & "'" & _
"addressZIPCODE='" & MaskedTextBoxZip.Text & "', phone='" & MaskedTextBoxPhone.Text & "', fax='" & MaskedTextBoxFax.Text & "', email='" & TextBoxEmail.Text & "'" & _
"WHERE accountNumber='" & TextBoxAccount.Text & "';", dbConn)
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
MessageBox.Show("Customer account SUCCESSFULLY updated!")
Call lockForm()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Call lockForm()
dbConn.Close()
Use MySQLCommand instead of MySQLDataAdapter. You are defeating the purpose of using ADONet because still your code is vulnerable with sql injection. Make it parameterized. Below is a modified code from your code. It uses Using-End Using for proper handling of object disposal.
Dim ConnectionString As String ="Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=trojan;Password=horse;Database=accounting"
Dim iQuery As String = "UPDATE customer " & _
"SET accountNumber = #accountNumber, nameLAST = #nameLAST, nameFIRST = #nameFIRST, " & _
" nameSALUTATION = #nameSALUTATION, nameCOMPANY = #nameCOMPANY, addressSTREET = #addressSTREET, " & _
" addressSTREET1 = #addressSTREET1, addressCITY = #addressCITY, addressSTATE = #addressSTATE, " & _
" addressZIPCODE = #addressZIPCODE, phone = #phone, fax = #fax, email = #email " & _
"WHERE accountNumber = #accountNumber"
Using dbConn As New MySqlConnection(ConnectionString)
Using dbComm As New MySQLCommand()
With dbComm
.Connection = dbConn
.CommandType = CommandType.Text
.CommandText = iQuery
.Parameters.AddWithValue("#accountNumber", TextBoxAccount.Text )
.Parameters.AddWithValue("#nameLAST", TextBoxLastName.Text)
.Parameters.AddWithValue("#nameFIRST", TextBoxFirstName.Text)
.Parameters.AddWithValue("#nameSALUTATION", ComboBoxSalutation.SelectedItem)
.Parameters.AddWithValue("#nameCOMPANY", TextBoxCompanyName.Text)
.Parameters.AddWithValue("#addressSTREET", TextBoxAddress1.Text)
.Parameters.AddWithValue("#addressSTREET1", TextBoxAddress2.Text)
.Parameters.AddWithValue("#addressCITY", TextBoxCity.Text)
.Parameters.AddWithValue("#addressSTATE", ComboBoxState.SelectedItem)
.Parameters.AddWithValue("#addressZIPCODE", MaskedTextBoxZip.Text)
.Parameters.AddWithValue("#phone", MaskedTextBoxPhone.Text)
.Parameters.AddWithValue("#fax", MaskedTextBoxFax.Text)
.Parameters.AddWithValue("#email", TextBoxEmail.Text)
End With
Try
dbConn.Open
dbComm.ExecuteNonQuery()
MessageBox.Show("Customer account SUCCESSFULLY updated!")
Call lockForm()
Catch( ex as MySQLException)
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
Finally
dbConn.Close()
End Try
End Using
End Using
In this case, I would use ExecuteNonQuery as you can't use a MySQLDataAdapter the way you are trying to use it. Also please use paramters as what you are doing opens you up to SQL injection attacks. And finally you don't need to update accountNumber because you are using that to find the row which you want to update!