Home >Database >Mysql Tutorial >How to Safely Use SQL's IN Statement with SqlParameter and a List?
SQL IN Statement with SqlParameter and List
When attempting to execute an IN statement with a SqlParameter using a List
Convert the List to an Array:
Convert the List
string[] paramArray = settingList.ToArray();
Format the SQL Statement:
Format the SQL statement with a placeholder for each parameter, using the number of parameters in the array:
string sql = "SELECT dscr FROM system_settings WHERE setting IN ({0})"; sql = string.Format(sql, string.Join(",", paramArray.Select((x, i) => "@settings" + i)));
Add Parameters:
For each element in the array, add a SqlParameter to the command object, using the appropriate name and value:
for (int i = 0; i < settingList.Count; ++i) { cmd.Parameters.Add(new SqlParameter("@settings" + i, settingList[i])); }
Execute the Command:
Execute the command as usual:
reader = cmd.ExecuteReader();
This approach provides a safe and efficient way to execute an IN statement with a List
The above is the detailed content of How to Safely Use SQL's IN Statement with SqlParameter and a List?. For more information, please follow other related articles on the PHP Chinese website!