有人知道为什么在cmd.ExecuteNonQuery()
上运行的代码为什么会出现异常?当我更新日期时,它运行得很好,但是当我更新完成日期时,出现了该错误。
这是代码
Call connection()
If txt_UpCom.Text = "" Or cbCom.SelectedItem = "" Then
If txt_ComNew.Enabled = True Then
MessageBox.Show("Please fill the entire data!")
End If
Else
Try
Dim str As String
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
cmd = New MySql.Data.MySqlClient.MySqlCommand(str, conn)
cmd.ExecuteNonQuery()
msgBoxSuccess.ShowDialog()
conn.Close()
Catch ex As Exception
MessageBox.Show("Unable to Update")
End Try
End If
答案 0 :(得分:0)
正如@JacekWróbel在评论中提到的那样,您应将列名保持在[](方括号)或“”(双引号)之间。表名(或与此相关的任何其他SQL对象)也一样。
长话短说,更改代码的这一部分:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
对此:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & comdate & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & txt_ComNew.Text & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
End If
注意:我希望保持事物的一致性,因此我向每个对象添加了[],无论它是否包含空格。