Javad-M
Javad-M

Reputation: 604

Read data from a SQL server

I have a Table with the name "MyTable". I want to read the "Active3" column When the "ID3" column is an specified value. But I get this error: Invalid attempt to read when no data is present.

    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()

Upvotes: 1

Views: 83

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

Try this:

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

Note: It's been a while since I've written VB.Net, there might be some mistakes here.

Explanations:

  • The Using block handles disposable objects correctly.
  • The use of parameters prevents Sql injection attacks
  • Using Reader.Read() instead of Reader.HasRows in the condition enables you to get the value of the current record.

SqlDataReader.Read() method Advances the SqlDataReader to the next record. It returns true if there are more records, and false otherwise. When the SqlDataReader is created, the default position is before the first row, so you must call the Read() method to get the values of the first row.

Upvotes: 2

Related Questions