Home >Database >Mysql Tutorial >Why Does My MySQL Parameterized Query in C# Throw an IndexOutOfBoundsException?
Parameterized Queries for MySQL with C#
This question addresses a common issue encountered when using parameterized queries with MySQL in C#. The provided code includes the relevant parts of the code that raise the issue.
Question:
The code snippet includes a parameterized query with two question marks (?) as placeholders for parameter values. However, the user experiences an IndexOutOfBoundsException when adding the first parameter. What's wrong with the code?
Answer:
The provided code initializes the MySqlCommand object with a parameterized query, but the placeholder question marks are not prefixed with the "@" character, which is required for named parameters in MySQL. The corrected code is as follows:
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; }
In this corrected code:
The above is the detailed content of Why Does My MySQL Parameterized Query in C# Throw an IndexOutOfBoundsException?. For more information, please follow other related articles on the PHP Chinese website!