display data from a mysql database column under label

Asked

Viewed 938 times

0

How to select a die from my table column and display it in a label?

EX:

id = 10 -> Banana
Select * From tabela where id = 10
label.Text = Banana


 MySqlConnection conexao = new MySqlConnection();
            conexao.ConnectionString = ("server=localhost; user id=root; pwd=root ;database=semi");
            conexao.Open();
            MySqlCommand command = new MySqlCommand();
            command.Connection = conexao;
            command.CommandText = "Select Valor_Venda from produtos where    Codigo = '" + comboBox4.Text + "'";
            MySqlDataReader dr = command.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            label20.Text = dr;

I found an example on the internet and tried to adapt more I believe I’m not on the right path. Can you help me? Any doubt of my question comment that I answer.

1 answer

0


In this your code, since you want only one value returned, you can do it directly by Executescalar.

It would look like this (I took your code as a base):

MySqlConnection conexao = new MySqlConnection();
conexao.ConnectionString = ("server=localhost; user id=root; pwd=root ;database=semi");
conexao.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = conexao;
command.CommandText = "Select Valor_Venda from produtos where    Codigo = '" + comboBox4.Text + "'";
string valor = command.ExecuteScalar().ToString("C");
label.Text = valor;
  • When making a query in the database involving some kind of parameters it is important to use the parameters @param pq will help you and prevent SQL Injection attacks.

  • I took his code and just added a few things, I didn’t modify. I also prefer to use parameters, but I didn’t know that it prevented attacks in this way, how does it work? You have a link explaining about this?

  • You can consult about SQL Injection here. And here is more information regarding the use of parameters in C#.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.