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?
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.
A parameterized query is a query in which placeholders ( %s ) are used for parameters (column values) and the parameter values supplied at execution time.
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 .
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; }
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With