如何在带有参数的SQL查询中使用通配符
假设我有一个基本查询,如下所示:
SELECT holiday_name FROM holiday WHERE holiday_name LIKE %Hallow%
这在我的SQL查询窗格中执行正常并返回’Halloween’。 当我尝试在我的代码中使用带有通配符’%’字符的参数时,会出现问题。
SqlConnection Connection = null; SqlCommand Command = null; string ConnectionString = ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString; string CommandText = "SELECT holiday_name " + "FROM holiday " + "WHERE holiday_name LIKE %@name%"; Connection = new SqlConnection(ConnectionString); try { Connection.Open(); Command = new SqlCommand(CommandText, Connection); Command.Parameters.Add(new SqlParameter("name", HolidayTextBox.Text)); var results = Command.ExecuteScalar(); } catch (Exception ex) { //error stuff here } finally { Command.Dispose(); Connection.Close(); }
这会引发错误的语法错误。 我已经尝试将’%’移动到我的参数中
Command.Parameters.Add(new SqlParameter("%name%", HolidayTextBox.Text));
但后来我收到一个错误,说我没有声明标量变量’@name’。 那么,如何正确格式化通配符以包含在查询参数中? 任何帮助表示赞赏!
首先,您的SqlParameter
名称是@name
而不是name
。
其次,我会移动你的通配符。
所以它看起来像这样:
string CommandText = "SELECT holiday_name " + "FROM holiday " + "WHERE holiday_name LIKE @name;" Connection = new SqlConnection(ConnectionString); try { var escapedForLike = HolidatyTextBox.Text; // see note below how to construct string searchTerm = string.Format("%{0}%", escapedForLike); Connection.Open(); Command = new SqlCommand(CommandText, Connection); Command.Parameters.Add(new SqlParameter("@name", searchTerm)); var results = Command.ExecuteScalar(); }
请注意, LIKE
在传递参数时需要特别小心,您需要转义一些字符使用sql参数在SQL LIKE语句中转义特殊字符 。
无论你做什么都不这样做 :
string CommandText = "SELECT holiday_name " + "FROM holiday " + "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
因为这将打开你的SQL注入,而不是这样做:
Command.Parameters.Add(new SqlParameter("@name", "%" + HolidayTextBox.Text + "%"));
您可能想了解Command.Parameters.AddWithValue,例如:
Command.Parameters.AddWithValue("@name", "%" + HolidayTextBox.Text + "%");
%
s应该是搜索字符串的一部分,而不是查询。
string CommandText = "SELECT holiday_name " + "FROM holiday " + "WHERE holiday_name LIKE @name"; Connection = new SqlConnection(ConnectionString); try { Connection.Open(); Command = new SqlCommand(CommandText, Connection); string name = "%" + HolidayTextBox.Text + "%"; Command.Parameters.Add(new SqlParameter("@name", name));