0

i have connected my database with my windows form, i put the values of my database table column at a listbox, and i want to do the following: when i select an item from the listbox, another column of the table will appear in another textbox. To be more specific, drink names appear at the listbox( espresso,water etc) and i want their price to appear at a textbox , when they are selected from the listbox. I used the following code to do that:

  private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string constring =      "datasource=localhost;port=3306;username=root;password=root;";
        string Query = "select * from apps.drinks where drink_name is ='" + listBox1.Text + "'; ";
        MySqlConnection conDatabase = new MySqlConnection(constring);
        MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
        MySqlDataReader myReader;
        conDatabase.Open();
        myReader = cmdDatabase.ExecuteReader();
        while (myReader.Read())
        {
            string dprice = myReader.GetString("drink_price");
            pricebox.Text = dprice;
        }

    }    

After i debug my project, it successfully shows the items at the listbox, but when i select them i get this error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '='Espresso'' at line 1"

The code from database is the following:

DROP TABLE IF EXISTS `apps`.`drinks`;
CREATE TABLE  `apps`.`drinks` (
  `drink_name` varchar(45) NOT NULL,
  `drink_price` varchar(45) NOT NULL,
  PRIMARY KEY (`drink_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into apps.drinks (drink_name,drink_price)
    values ('Nes','1'),('Espresso','1'), (...)    

Please can you help me??

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953

1 Answers1

1

The query where it fails on is:

"select * from apps.drinks where drink_name is ='" + listBox1.Text + "'; "

there you have is = which is incorrect, remove is so the query looks like:

"select * from apps.drinks where drink_name ='" + listBox1.Text + "'; "

Also take the comment of w0lf seriously and use prepared statements to prevent SQL injection.

Community
  • 1
  • 1
huysentruitw
  • 27,376
  • 9
  • 90
  • 133