0

我正在尝试在用户修改数据库记录时更新它。我有一个名为“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
4

2 回答 2

1

将您的 UPDATE 语句更改为以下形式:

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

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

于 2013-11-06T19:54:54.047 回答
1

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

oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
oledbCmd.CommandText = "INSERT INTO [TableName] ([Fieldname1], [Fieldname2]) VALUES (?,?)"
oledbCmd.Parameters.Add( .... )
oledbCmd.Parameters.Add( .... )
oledbCmd.ExecuteNonQuery()
于 2013-11-06T15:32:10.230 回答