C# 将运行时错误获取为";必须声明标量变量@name";
我得到的运行时错误是“必须声明标量变量@name”C# 将运行时错误获取为";必须声明标量变量@name";,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我得到的运行时错误是“必须声明标量变量@name” 对于串联字符串查询,请尝试使用参数化。但是您忘记在执行命令之前将参数添加到命令中。这导致了这里的问题。可以使用以下代码为指定的参数添加值 str = "select balanceamount from wallet where username LIKE @name"; com = new SqlCommand(str, con); com.Parameters.AddWithValue(@name, "%" + name + "%");
对于串联字符串查询,请尝试使用参数化。但是您忘记在执行命令之前将参数添加到命令中。这导致了这里的问题。可以使用以下代码为指定的参数添加值
str = "select balanceamount from wallet where username LIKE @name";
com = new SqlCommand(str, con);
com.Parameters.AddWithValue(@name, "%" + name + "%");
SqlDataReader reader = com.ExecuteReader();
// Process with reader
要在
SqlCommand
中使用参数,应将它们添加到参数
字典():
将%
s移动到字符串值也有意义,以避免运行时连接:
com.Parameters.Add("@name", "%JohnSmith%");
如果代码中有一个包含名称的字符串变量(确实有),则:
只需在ExecuteReader之前为查询添加
SqlParameter
:com.Parameters.AddWithValue(“@name”,name)
。您没有为SQL查询声明@name,因此错误消息是正确的。这是代码转储,不是问题。
com.Parameters.Add("@name", "JohnSmith");
com.Parameters.Add("@name", "%JohnSmith%");
string name = (string) Session["name"];
com.Parameters.Add("@name", $"%{name}%");