kielou
kielou

Reputation: 437

Getting values from database to label

how can i get values from database to a label when i type an ID number and use a button? i'm just new in C#

here is what i got so far but its not working

String str = @"server=localhost;database=library;userid=root;password=1234;";
MySqlConnection con =  new MySqlConnection(str);


con = new MySqlConnection(str);
con.Open();
String cmdText = "SELECT * FROM `book` WHERE `Book ID` = '"+txtbnumber+"'";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
MySqlDataReader myReader;



try
{
    con.Open();
    myReader = cmd.ExecuteReader();

    while (myReader.Read())
    {
        String tittle = myReader.GetString("Tittle");
        String author = myReader.GetString("Author");


        lbltittle.Text = tittle;
        lblauthor.Text = author;
    }

}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Upvotes: 0

Views: 80

Answers (1)

Jan Köhler
Jan Köhler

Reputation: 6030

Replace

String cmdText = "SELECT * FROM `book` WHERE `Book ID` = '"+txtbnumber+"'";

by

string cmdText = "SELECT * FROM [book] WHERE [Book ID] = " + txtbnumber;

But this is still quite prone to sql injection. So you should prefer using parameterized queries:

string cmdText = "SELECT * FROM [book] WHERE [Book ID]=@BookNumber";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.AddWithValue("@BookNumber", Convert.ToInt32(txtbnumber.Text));

Upvotes: 1

Related Questions