This is my code i'm trying to update table via VB forms , I don't know what the wrong with it please help me.
This is the table:
Dim con As New OleDbConnection("provider=microsoft.ace.oledb.12.0; data source = |datadirectory|\Studen.accdb;")
con.Open()
Dim sql As String = "Update tend set StudentName='" & TextBox9.Text & "', LessonDate='" & TextBox13.Text & "', LessonTime=" & TextBox10.Text & ", Payment=" & TextBox11.Text & ", Note='" & TextBox12.Text & "' where ID=" & TextBox8.Text
Dim cmd As New OleDbCommand(sql, con)
cmd.ExecuteNonQuery()
con.Close()
The first problem is the field named NOTE. This is a reserved keyword in MS-Access and, if you want to use it, you need to encapsulate the word with square brackets
Dim sql As String = "Update tend set StudentName=...., [Note]=..."
but this is not the only problem here. A much bigger one is the string concatenation used to build the sql command. This approach leads to possible sql injections and problems in propertly quoting the values used to prepare the statement. Strings need to be examined to duplicate single quotes, decimals need to be passed with the proper decimal point, dates need to be encapsulated in the # symbol and so on....
A better way is using a parameterized query
Dim sql As String = "Update tend set StudentName=?, LessonDate=?, LessonTime=?, " & _
"Payment=?, [Note]=? where ID=?"
Using con = New OleDbConnection(...........)
Using cmd = New OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("@p1", TextBox9.Text)
cmd.Parameters.AddWithValue("@p2", Convert.ToDate(TextBox13.Text))
cmd.Parameters.AddWithValue("@p3", Convert.ToInt32(TextBox10.Text))
cmd.Parameters.AddWithValue("@p4", Convert.ToDecimal(TextBox11.Text))
cmd.Parameters.AddWithValue("@p5", TextBox12.Text)
cmd.Parameters.AddWithValue("@p6", Convert.ToInt32(TextBox8.Text))
cmd.ExecuteNonQuery()
End Using
End Using
In a parameterized query, like the one above, you put placeholders (?) in the query text and supply the values with the Parameters collection of the command. In this way, the work to properly quote every single value is passed to the framework and db engine. They know better than you and me how to properly quote the parameters.
Note how the AddWithValue method infers the correct datatype to use for the parameter looking at the datatype of value passed. If your LessonDate field is a field with DateTime type then you need to convert the textbox text (a string) to a date. This could cause an exception if you don't check before trying the conversion. (Here I assume that you have something in place to ensure valid inputs). The same reasoning should be applied to the other NON text fields. (ID, LessonTime, Payment)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.