0

Getting Error While Updating Record.

Firs of all i select a row from Datagrid then selected row's values displayed to textbox then i click update button to update record. After entered New usename and password click save Buton then getting error as follow.

ERROR
system.data.oledb.oledbException(0x80040e14):syntax error in UPDATE statement.
at
system.data.oledb.oledbCommand.executeCommandTextErrorHandling(Oledb Hresult hr)
at
System.data.Oledb.OledbCommand.ExecutecommandTextforSingleResult(tagDBPARAMS dbParams,
Object& executeResult)
at
System.data.Oledb.OledbCommand.Executecommand(CommandBehavior Behavior, String method)
at System.data.Oledb.OledbCommand.ExecuteNonQuery()
at Nakul.frmusers.cmdsave_click(object sender, EventArgs e)in
E:\kul....\frmusers.vb:line 152


Note : I did not want to update the userid.

Data.accdb // Access File Name
table Name : users
Design View: userid   Number     // primary key
                      username   text
                      password   text

Imports System.Data
Imports System.Data.OleDb
public class users

Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\kul\Data.accdb;Persist Security Info=False;"

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click

    Dim conn As New OleDbConnection(str)
    Dim qry As New OleDbCommand("update users set username='" & txtusername.Text & "', password='" & txtpassword.Text & "' where userid=" & txtuserid.Text, conn)

            Try
                conn.Open()
                qry.ExecuteNonQuery()       // Error Line No 152 in Coading
                conn.Close()
                MsgBox("Record Updated")
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
 End Sub
End class
4

1 回答 1

0

语法错误的主要原因是单词 PASSWORD。它是 Access 中的保留关键字,因此您需要用方括号将其封装起来

也就是说,您需要更改查询并使用参数化方法,而不是字符串连接。构建查询连接字符串可能是语法错误的另一个来源(包含单引号的用户名?)并为 sql 注入攻击打开了大门

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click

    dim query = "update users set username=?, [password]=? where userid=?"
    Using conn = new OleDbConnection(str)
    Using qry = New OleDbCommand(query, conn)
        qry.Parameters.AddWithValue("@p1",txtusername.Text )
        qry.Parameters.AddWithValue("@p2",txtpassword.Text )
        qry.Parameters.AddWithValue("@p3",Convert.ToInt32(txtuserid.Text))
        conn.Open()
        qry.ExecuteNonQuery()       
        conn.Close()
        MsgBox("Record Updated")
    End Using
    End Using
 End Sub

还要注意确保正确关闭和处理连接和命令的 using 语句。

于 2013-06-13T13:09:56.730 回答