我在根据另一个查询运行查询时遇到了一些问题。这是给出一点背景的数据库图。所有表的主键由identites自动生成。前2个插入语句(Donation和Food_Donation)有效,但我无法将最后一个插入到Donation_Details中。这是迄今为止的代码:
Dim con As New OleDbConnection(DBcon)
Try
Dim dr As OleDbDataReader
Dim command As New OleDbCommand("Insert into Donation (Donor_ID) VALUES ( " & txtDonNum.Text & "); Select @@Identity;")
con.Open()
command.Connection = con
dr = command.ExecuteReader
Dim Donation_ID As String = ""
If dr.Read() Then
Donation_ID = dr(0).ToString
Dim food As New OleDbCommand("Insert into Food_Donation (Date_Received, Donation_ID) Values ( '" & maskedreceived.Text & "', " & Donation_ID & "); Select @@Identity")
food.Connection = con
food.ExecuteNonQuery()
End If
Dim Food_ID As String = ""
If dr.Read() Then
Food_ID = dr(0).ToString
Dim food2 As New OleDbCommand("Insert into Donation_Details (Quantity, Unit, Expiration_Date, Food_ID, Storage_ID, Type_ID) Values ( " & txtQuantity.Text & ", '" & boxUnit.Text & "', '" & maskedexpire.Text & "', " & Food_ID & ", " & txtStorageID.Text & ", " & txtTypeID.Text & ")")
food2.Connection = con
food2.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Close()
End Try
结束子
我相当正确我的SQL语句是正确的,只是最后的语句是否需要是If或其他语句。
答案 0 :(得分:0)
如果您想重新使用dr来获取dr = food.ExecuteReader()
,那么您应该使用food.ExecuteNonQuery()
而不是Food_ID
?
答案 1 :(得分:0)
我怀疑您的问题是您使用If dr.Read()
两次。
dr.Read()
方法会将阅读器向前移动到下一行,但您只在初始查询中选择一个值。
因此,例如,您的阅读器(由插件制作)将为成功插入返回单行值。在其上调用Read()
会成功,但会将行光标移至EOF
,导致后续Read()
次调用返回FALSE