Danielle Neil
Danielle Neil

Reputation: 13

Using SQL datareader to set variables to a label

I have spent so long on figuring this out however cant seem to resolve the problem. I am using MySql and Visual Basic.

I am using the select statement to get the variables i need, then using data reader to loop through, get the variables (to string) and finally set these to text labels which I am using in a form. I am sure I am following the correct procedure for this, but this does not seem to bring back results.

If anybody could help me i would be very much appreciated. The code I have is below;

    lblName.Text = Form1.topicName

    MyConnString = "Database=case management system;Data Source=localhost;User Id=root;Password="abc"
    Dim MySqlConn As New MySqlConnection(MyConnString)
    Dim MySelectQuery As String = "SELECT topic_id, topic_name, description, useful_links, employee_id, date "             
       & "FROM knowledge_base "
       & "WHERE topic_name = '" & lblName.Text & "'"
    Dim myCommand As New MySqlCommand(MySelectQuery)
    myCommand.Connection = MySqlConn
    MySqlConn.Open()
    myCommand.ExecuteNonQuery()
    mydata = myCommand.ExecuteReader
    While mydata.Read()
        labelDescription.Text = mydata.Item("description").ToString
        labelLinks.Text = mydata.Item("useful_links").ToString
    End While
    mydata.Close()
    myCommand.Connection.Close()
    MySqlConn.Close()

Upvotes: 1

Views: 601

Answers (1)

Richard Schneider
Richard Schneider

Reputation: 35477

Remove the line containing myCommand.ExecuteNonQuery(). You are doing query!

Also, the labels (descriptions and links) will only contain the last data from the last row returned.

Adding text input directly to a SQL command allows a SQL injection attack. You should use sql parameters. See http://www.dotnetperls.com/sqlparameter

Upvotes: 1

Related Questions