我正在尝试使用按钮上的以下代码运行我的系统但是我得到一个很长的错误(我要发布一个链接到屏幕截图,因为我没有足够的声誉。)谢谢! http://i.imgur.com/MM2GP00.png 以下是代码:
Private Sub Button8_Click(sender As System.Object, e As System.EventArgs) Handles Button8.Click
Try
Dim sqlquery As String = "UPDATE books SET Title = @titl, Author = @aut, " & _
"WHERE ID = " & DataGridView2.SelectedRows(0).Cells(0).Value.ToString & ";"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("@titl", TextBox2.Text)
cmd.Parameters.AddWithValue("@aut", TextBox3.Text)
If TextBox2.Text = "" Or TextBox3.Text = "" Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("A record has been successfully updated!", "Updated!")
dtgrd()
Else
MessageBox.Show("Failed to update record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
答案 0 :(得分:0)
您的SQL查询Author = @aut,
中有额外的逗号,请尝试删除
在代码中替换
Dim sqlquery As String = "UPDATE books SET Title = @titl, Author = @aut " & _
"WHERE ID = " & DataGridView2.SelectedRows(0).Cells(0).Value.ToString & ";"
还有一件事,就是在打开连接后检查代码中的文本框空值,在执行任何操作之前尝试执行该验证。然后你的代码将是这样的
Private Sub Button8_Click(sender As System.Object, e As System.EventArgs) Handles Button8.Click
Try
If TextBox2.Text = "" Or TextBox3.Text = "" Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
Return
End If
Dim sqlquery As String = "UPDATE books SET Title = @titl, Author = @aut " & _
"WHERE ID = " & DataGridView2.SelectedRows(0).Cells(0).Value.ToString & ";"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("@titl", TextBox2.Text)
cmd.Parameters.AddWithValue("@aut", TextBox3.Text)
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("A record has been successfully updated!", "Updated!")
dtgrd()
Else
MessageBox.Show("Failed to update record!", "Failure!")
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub