在vb.net中更新数据库导致语法错误

时间:2013-11-06 15:24:31

标签: vb.net visual-studio-2010

我正在尝试在用户修改数据库记录时更新数据库记录。我有一个名为'txtColsTextBox'的文本框,它存储了值和一个名为'btnSaveExit'的按钮。在按钮单击时,我需要使用新值更新数据库。

我将如何根据我的代码执行此操作。我在想,我需要使用me.validate函数,但不知道如何编码。感谢

Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbCmd As OleDbCommand
Dim sql As String

connetionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\domain\storage.accdb"
sql = "SELECT Cols FROM Racks Where [Rack code] = '" & buttonName & "'"
    oledbCnn = New OleDbConnection(connetionString)
Try
    oledbCnn.Open()
    oledbCmd = New OleDbCommand(sql, oledbCnn)
    Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
    While oledbReader.Read
        'MsgBox(oledbReader.Item(0))
        txtColsTextBox.Text = oledbReader.Item(0)
    End While
    oledbReader.Close()
    oledbCmd.Dispose()
    oledbCnn.Close()
Catch ex As Exception
    MsgBox(ex.Message)
End Try

编辑:更新数据库的代码

Private Sub btnSaveExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveExit.Click
        Try
            connetionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\domain\storage.accdb"

            oledbCnn.Open()
            oledbCmd = New OleDbCommand(sql, oledbCnn)
            oledbCmd.CommandText = "UPDATE [Racks] SET [Cols] VALUES (?)"
            oledbCmd.Parameters.AddWithValue("@Cols", txtColsTextBox.Text)
            oledbCmd.ExecuteNonQuery()

            MessageBox.Show("Record succesfully updated" + txtColsTextBox.Text)

        Catch ex As Exception
            MessageBox.Show(ex.Message)

        End Try
    End Sub

2 个答案:

答案 0 :(得分:1)

为了表明你要开始,你可以使用这样的东西(调整表名,字段名和参数)

oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
oledbCmd.CommandText = "INSERT INTO [TableName] ([Fieldname1], [Fieldname2]) VALUES (?,?)"
oledbCmd.Parameters.Add( .... )
oledbCmd.Parameters.Add( .... )
oledbCmd.ExecuteNonQuery()

答案 1 :(得分:1)

将UPDATE语句更改为以下格式:

UPDATE [Racks] SET [Col1] = ?, [Col2] = ? WHERE [IdCol] = ?

该示例假定您要使用新值更新Col1和Col2,并且仅针对一条记录(IdCol等于id的记录)。按照与UPDATE语句中的顺序对应的顺序添加参数。