Asp.net 从SQL server读取数据
我有一张名为“MyTable”的桌子。当“ID3”列是指定值时,我想读取“Active3”列。但我得到了这个错误:当没有数据存在时,无效的读取尝试Asp.net 从SQL server读取数据,asp.net,sql-server,vb.net,Asp.net,Sql Server,Vb.net,我有一张名为“MyTable”的桌子。当“ID3”列是指定值时,我想读取“Active3”列。但我得到了这个错误:当没有数据存在时,无效的读取尝试 Dim con1 As New SqlConnection(connectionString) con1.Open() Dim sql1 As String = String.Format("SELECT Active3,DateTime3,BuyDateTime3 FROM MyTable WHERE ID3='{0}'",
Dim con1 As New SqlConnection(connectionString)
con1.Open()
Dim sql1 As String = String.Format("SELECT Active3,DateTime3,BuyDateTime3 FROM MyTable WHERE ID3='{0}'", Session("lblID8"))
Dim command1 As SqlCommand = New SqlCommand(sql1, con1)
Dim reader As SqlDataReader = command1.ExecuteReader
If reader.HasRows Then
Label4.Text = reader("Active3")
else
End If
con1.Close()
试试这个:
Using con1 As New SqlConnection(connectionString)
con1.Open()
Dim sql1 As String = "SELECT Active3,DateTime3,BuyDateTime3 FROM MyTable WHERE ID3=@ID3"
Dim command1 As SqlCommand = New SqlCommand(sql1, con1)
command1.Parameters.AddWithValue("@ID3", Session("lblID8"))
Using reader As SqlDataReader = command1.ExecuteReader
If reader.Read() Then
Label4.Text = reader("Active3")
else
End If
End Using
End Using
注意:我已经有一段时间没有写VB.Net了,这里可能有一些错误
说明:
块可正确处理一次性对象使用
- 使用参数可以防止Sql注入攻击
- 在条件中使用
而不是Reader.Read()
,可以获取当前记录的值李>Reader.HasRows
true
,否则返回false
。
创建SqlDataReader时,默认位置是第一行之前的,因此必须调用
Read()
方法来获取第一行的值。而确切的错误消息是?开始告诉我们错误。哦,试着自己调试一下。到目前为止,答案是“学习编程”。考虑到您提供的信息量,这是唯一可能的答案。另外,请:永远不要使用类似于WHERE ID3='{0}'
的任何东西。您正在打开数据库以进行最坏类型的攻击。请查看如何使用SQL参数。不要使用string.Format()
创建SQL-这将启用SQL注入!对我来说也有一段时间了,但是在使用DataReader之前是否需要Read()调用?@AdamV:在访问数据之前,是的。来自MSDN:“SqlDataReader的默认位置在第一条记录之前。因此,您必须调用Read来开始访问任何数据。”此行中有一个错误:command1.Parameters.Add(“@ID3”SqlDbType.int)。Value=Session(“lblID8”)
“value”不是“integer”的成员请确保您没有丢失)
SqlDbType.int和值之间的)