【发布时间】:2020-12-06 13:27:36
【问题描述】:
我正在尝试按照YT tutorial 从 MS 数据库中删除一行,但我遇到了 2 种错误。当我尝试这个时:
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "C:\Users\user\Desktop\PU\SEMESTER 4\Visual Programming\Hospital Databases\Patient DB.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Delete * from [Patient] Where [PatientID] = " & PatientID.ToString & ""
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
我收到此错误:“查询表达式中的格式错误的 GUID '[PatientID]=DataGridViewTextBoxColumn { Name=PatientID, index=0 }'
所以我使用了here 中的括号,所以现在是这样的:
str = "Delete * from [Patient] Where [PatientID] = [" & PatientID.ToString & "]"
但这给出了一个错误:“没有为一个或多个必需参数提供值”。当我用单引号替换括号时,我也会收到此错误。
想知道该怎么做。
编辑:
我之所以选择PatientID.ToString,是因为我想让它在用户单击 ID 单元格时,无需用户输入任何内容即可获得 ID。但显然那是错误的,所以我做了一个输入框并按照玛丽的回答。但我在Execute... 行收到此错误:
"没有为一个或多个必需参数指定值"
我进行了搜索,其中大多数人都说要加上单引号才能使其正常工作。我做了 (^) 并且仍然得到那个错误:(我是否以错误的方式调用 sub?
Private Sub DischargeToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles DischargeToolStripMenuItem1.Click
Dim ID As Integer
ID = InputBox("Enter the ID of the patient to be discharged", "Discharge")
DeleteRecord(ID)
End Sub
Sub DeleteRecord(ID As Integer)
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Dim dataFile = "C:\Users\user\Desktop\PU\SEMESTER 4\Visual Programming\Hospital Databases\Patient DB.accdb"
Dim connString = provider & dataFile
Using myConnection As New OleDbConnection(connString),
cmd As New OleDbCommand("Delete * from Patient Where PatientID = @ID", myConnection)
cmd.Parameters.Add("@ID", OleDbType.Integer).Value = ID
myConnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
【问题讨论】:
-
当你 debug.print str 的值你得到什么?给您的提示是首先让 SQL 查询在 Access 中工作,然后将其用作构建所需的确切字符串的指南。从这个问题很可能你只需要这个: Where [PatientID] = '" & PatientID.ToString & "'"
-
根据错误消息,
PatientID是DataGridView中的一列。这意味着你不仅使用了糟糕的、误导性的名称,而且使用了错误的东西。如果您想要的实际值在网格中一行的单元格中,那么您需要从网格行的单元格中获取该值,而不是使用列。此外,停止使用字符串连接将值插入 SQL 代码并学习如何使用参数。 -
如果你能告诉我们
PatientID来自哪里会很有帮助