SQL read data from table into vb

I am trying to get one field back from data. (I am looking at the primary key, so I should get 0 or 1 response). Please help. The table I'm querying has one entry with user = someone entering in multiple columns with the ans column having a "good answer"


The code:

Dim reader As SqlDataReader
Dim par As SqlParameter
Dim result As String

Dim sqlconn As SqlConnection
sqlconn = New SqlConnection("....")
sqlconn.Open()

Dim sqlcmd As SqlCommand
sqlcmd = New SqlCommand("Select Ans From Test Where User = @auser", sqlconn)

par = New SqlParameter
par.ParameterName = "auser"
par.Value = Textbox1.Text

sqlcmd.Parameters.Add(par)

reader = sqlcmd.ExecuteReader()

result = reader.GetString(0)

''//output to label
label1.Text = result

      

+1


a source to share


2 answers


You need to read the data reader first to put it on the first line.

So instead of

reader = sqlcmd.ExecuteReader()    
result = reader.GetString(0)

      



You have to insert the Read () method like this:

reader = sqlcmd.ExecuteReader()    
if reader.Read() then '' <<<<< newly inserted code
    result = reader.GetString(0)
end if

      

+4


a source


''// using statement will guarantee the object is closed and disposed
''// even if an exception occurs
Using sqlconn As New SqlConnection("...."), _
      sqlcmd As  New SqlCommand("Select Ans From Test Where User = @auser", sqlconn)

    ''// you can create, add, and set the value for a parameter all on one line
    sqlcmd.Parameters.Add("@auser", SqlDbType.VarChar, 50).Value = Textbox1.Text

    ''//wait as long as possible to open the connection
    sqlconn.Open() 

    ''// if you're only getting the first column of the first row, use execute scalar
    label1.Text = CString(sqlcmd.ExecuteScalar())

End Using

      



0


a source







All Articles