假设我有一个基本查询,如下所示:
SELECT holiday_name
FROM holiday
WHERE holiday_name LIKE %Hallow%
这在我的sql查询窗格中执行良好,并返回“万圣节”。当我尝试在代码中使用带通配符'%'的参数时,会出现我的问题。
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语句中转义特殊字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句