【问题标题】:Read data from a SQL server从 SQL 服务器读取数据
【发布时间】:2016-03-20 13:02:11
【问题描述】:

我有一个名为“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}'", 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()

【问题讨论】:

  • 准确的错误信息是...?
  • 开始告诉我们错误。哦,尝试自己调试它。到目前为止,答案是“学习编程”。考虑到您提供的信息量,唯一可能的答案。
  • 请:永远永远永远使用WHERE ID3='{0}'之类的东西。您正在为最糟糕的攻击打开数据库。请查看如何使用 SQL 参数。
  • 不要使用string.Format()创建SQL - 这会启用SQL注入!

标签: asp.net sql-server vb.net


【解决方案1】:

试试这个:

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 块正确处理一次性对象。
  • 使用参数防止Sql注入攻击
  • 在条件中使用Reader.Read() 代替Reader.HasRows 可以获取当前记录的值。

SqlDataReader.Read() 方法 将 SqlDataReader 前进到下一条记录。如果有更多记录,则返回true,否则返回false。 创建SqlDataReader时,默认位置是第一行之前,所以必须调用Read()方法获取第一行的值。

【讨论】:

  • 对我来说也有一段时间了,但是在您使用 DataReader 之前不需要调用 Read() 吗?
  • @AdamV:在您访问数据之前,是的。来自 MSDN:“SqlDataReader 的默认位置在第一条记录之前。因此,您必须调用 Read 才能开始访问任何数据。”
  • 这一行有错误:command1.Parameters.Add("@ID3" SqlDbType.int).Value = Session("lblID8")
  • 'value' 不是'integer'的成员
  • 确保你没有错过SqlDbType.int.Value之间的)
猜你喜欢
  • 2013-11-23
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多