Vb.net 长update语句错误?
我试着用按钮上的以下代码运行我的系统,但我遇到了一个长错误,我要发布一个屏幕截图链接,因为我没有足够的声誉。非常感谢。 代码如下:Vb.net 长update语句错误?,vb.net,select,Vb.net,Select,我试着用按钮上的以下代码运行我的系统,但我遇到了一个长错误,我要发布一个屏幕截图链接,因为我没有足够的声誉。非常感谢。 代码如下: 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
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
您的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
在Author=@aut后面有一个逗号,请删除它。这只是一个简单的打字错误,如果你不想被否决票淹没,你可以修改它并删除这个问题。作为旁注,请尝试阅读有关参数化查询的内容,以及为什么应该始终对传递给数据库的每个值使用参数化查询