Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized Query for MySQL with C#

Tags:

c#

mysql

I have the code below (I've included what I believe are all relevant sections):

private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_@ = ?;"; public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.Add(new MySqlParameter("", val1));     m.Parameters.Add(new MySqlParameter("", val2));     MySqlDataReader r = m.ExecuteReader();     if (r.HasRows)         level = Convert.ToInt32(r.GetValue(0).ToString());     r.Close();     return true; } 

When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?

like image 211
Elie Avatar asked Mar 17 '09 03:03

Elie


People also ask

How write parameterized SQL query in C?

Using parameterized queries is a three-step process: Construct the SqlCommand command string with parameters. Declare a SqlParameter object, assigning values as appropriate. Assign the SqlParameter object to the SqlCommand object's Parameters property.

What is parameterized query in MySQL?

A parameterized query is a query in which placeholders ( %s ) are used for parameters (column values) and the parameter values supplied at execution time.

How do I write a parameterized query in SQL?

Declare statements start with the keyword DECLARE , followed by the name of the parameter (starting with a question mark) followed by the type of the parameter and an optional default value. The default value must be a literal value, either STRING , NUMERIC , BOOLEAN , DATE , or TIME .


2 Answers

Try this instead:

private String readCommand =               "SELECT LEVEL FROM USERS WHERE VAL_1 = @param_val_1 AND VAL_2 = @param_val_2;";  public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.AddWithValue("@param_val_1", val1);     m.Parameters.AddWithValue("@param_val_2", val2);     level = Convert.ToInt32(m.ExecuteScalar());     return true; } 
like image 172
Chris Avatar answered Sep 18 '22 04:09

Chris


protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {     MySqlConnection con = new MySqlConnection("server=localhost;User Id=root;database=result;password=1234");     con.Open();      MySqlCommand cmd = new MySqlCommand("Select * from users where username=?username and password=?password", con);     cmd.Parameters.Add(new MySqlParameter("username", this.Login1.UserName));     cmd.Parameters.Add(new MySqlParameter("password", this.Login1.Password));       MySqlDataReader dr = cmd.ExecuteReader();     if (dr.HasRows ==true)     {         e.Authenticated = true;     } } 
like image 45
Ujjwal Wagle Avatar answered Sep 22 '22 04:09

Ujjwal Wagle