2011-05-04 201 views
0

基於這個VB代碼,我得到了一切在我的SQL數據庫中正確創建,而不是顯示在txtfoodid中的Food_ID它彈出在消息框中(我認爲這是因爲Try/Catch )。文本框顯示不正確

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 
      dr = food.ExecuteReader() 
      'food.ExecuteNonQuery() 
     End If 
     Dim Food_ID As String 
     If dr.Read() Then 
      Food_ID = dr(0).ToString 
      txtfoodid.Text = dr("Food_ID").ToString 
     End If 

    Catch ex As Exception 

     MessageBox.Show(ex.Message) 
    Finally 
     con.Close() 
    End Try 

    MessageBox.Show("Food_ID has been made.") 

End Sub 

我試過多種方式讓它顯示,但沒有任何工作到目前爲止。

回答

1

您正在引用列txtfoodid.Text = dr(「Food_ID」)。ToString但您的Select語句僅返回@@ Identity。

該閱讀器沒有返回Food_ID列。或者用它自己的閱讀器創建一個新的Select查詢,或者修改第二個語句以返回Food_ID列。

另外在這裏你的代碼是非常容易受到SQL注入的攻擊類型,並建議閱讀Stop Sql Injection Attacks Before They Stop You

0

鹼式大多是正確的。唯一的是,你有你需要的信息。基本上,只是改變這一行

txtfoodid.Text = dr("Food_ID").ToString 

txtfoodid.Text = Food_ID 

,你會好到哪裏去。當您已經獲取並將其分配給變量Food_ID時,您正試圖從DataReader中讀取Food_ID。