我正在制作一个程序,我正在创建一个部分,当您输入客户ID时,它将删除该记录。问题是,如果你输入id 30并且没有30它仍会继续并删除它,即使没有该id的记录。我想让它显示一条消息说没有记录存在,但我的下面的代码不会起作用。我感到很困惑!
我在这里找到了代码,我试图将其应用到我的设计中,但它并不起作用。如您所见,我标记了我的原始代码,但我尝试使用这个新代码。求救!
我在运行时收到的错误是:不支持关键字:'提供商'
代码:
Private Sub Client(ByVal ans As String)
Dim con1 As SqlConnection = New SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.\Database.accdb")
If con1.State = ConnectionState.Closed Then con1.Open()
Dim theQuery As String = "SELECT * FROM tbl WHERE ID = ?"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con1)
cmd1.Parameters.AddWithValue("?", OleDbType.VarChar).Value = ans
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User exists delete
Dim cmd As SqlCommand = New SqlCommand("DELETE FROM tbl where ID = ?", con1)
cmd.ExecuteNonQuery()
Else
' User does not exist throw message
MsgBox("Records dont exist", MsgBoxStyle.Information, "Add New Customer!")
End If
End Using
con1.Close()
End Sub
答案 0 :(得分:1)
由于我使用SQL语句连接到ACCESS数据库,因此无法正常工作,所以我需要回到自己的根源并使用正确的 OleDb 语句。 我的案例中可行的代码如下:
Private Sub DeleteClient(ByVal ans As String)
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "DELETE FROM tbl WHERE ID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
If cmd.ExecuteNonQuery() = 0 Then
MsgBox("ID Does not exist!", MsgBoxStyle.Critical, "Enter new customer ID!")
Else
MessageBox.Show("The entered ID has now been deleted.", "Deletion Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
cmd.ExecuteNonQuery()
con.Close()
End Sub