文本框显示不正确
问题描述:
基于这个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
我试过多种方式让它显示,但没有任何工作到目前为止。
答
您正在引用列txtfoodid.Text = dr(“Food_ID”)。ToString但您的Select语句仅返回@@ Identity。
该阅读器没有返回Food_ID列。或者用它自己的阅读器创建一个新的Select查询,或者修改第二个语句以返回Food_ID列。
另外在这里你的代码是非常容易受到SQL注入的攻击类型,并建议阅读Stop Sql Injection Attacks Before They Stop You
答
碱式大多是正确的。唯一的是,你有你需要的信息。基本上,只是改变这一行
txtfoodid.Text = dr("Food_ID").ToString
到
txtfoodid.Text = Food_ID
,你会好到哪里去。当您已经获取并将其分配给变量Food_ID时,您正试图从DataReader中读取Food_ID。