开发者

Multiple if statements, then, or else?

I'm having some problems getting a query to run based off another query. Here's the database diagram to give a little background. The primary keys for all the tables are automatically generated by identites. The first 2 insert statements (Donation and Food_Donation) work but I can't get the last insert into Donation_Details to work. Here's the code so far:

Dim con As New OleDbConnection(DBcon)

Try
    Dim dr As OleDbDataReader
    Dim command As New Ole开发者_运维百科DbCommand("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

End sub

I'm fairly correct my SQL statements are correct and it's just whether or not the last statements need to be an If or something else.


You should be using dr = food.ExecuteReader() rather than food.ExecuteNonQuery() if you want to reuse dr to acquire Food_ID?


I suspect your problem is that you're using If dr.Read() twice.

The dr.Read() method will move the reader forward to the next row but you are only selecting a single value in your initial query.

So, for example, your reader (being made from the insert) will return a single row value for the successful insert. Calling Read() on it will succeed but then move the row cursor to EOF causing subsequent Read() calls to return FALSE

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜