我有一个名为“ MyTable”的表。我想读取“ Active3”列当“ ID3”列为指定值时。但是我收到此错误:没有数据时,读取尝试无效。
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以来已经有一段时间了,这里可能会有一些错误。
说明:
Using
块正确处理一次性的对象。Reader.Read()
代替代替Reader.HasRows
使您能够获取当前记录的值。SqlDataReader.Read()
方法将SqlDataReader前进到下一条记录。true
如果有更多记录,false
则返回,否则返回。创建SqlDataReader时,默认位置在第一行之前,因此您必须调用该Read()
方法以获取第一行的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句