0

I have a MySql database and I want to assign sql query result to a variable. How can I do this?

My query:

sql = "SELECT rol FROM users WHERE user = '" + txtUser.Text + "'"
3
  • 1
    Start reading about ADO.NET. Also google for 'query database with C#' Commented Mar 15, 2014 at 19:44
  • 1
    @SergeyBerezovskiy: Yes. Other than the OP you are not Lazy anymore! Commented Mar 15, 2014 at 19:46
  • Out of topic, but you should try to find something about SQL Injections Commented Mar 15, 2014 at 19:47

1 Answer 1

2
void AssignValue()
{
    using(MySqlConnection con =new MySqlConnection("/*connection string here*/"))
    using(MySqlCommand command = new MySqlCommand("SELECT rol FROM users WHERE 
                                 user = @user",con))
    {
      con.Open();
      command.Parameters.AddWithValue("@user",txtUser.Text);        
      TextBox2.Text = commad.ExecuteScalar().ToString();        
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

The command parameters are a good point. Better enclose the connection in a using statement. This ensures that it will be closed, even if an exception occurs.
Error 1 The name 'roleName' does not exist in the current context
@user3421239: are you able to run it now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.