C# 在SqlCommand查询中传递值时出错
我做错了什么?我只需要一个动态方法,它可以根据值对任何列进行计数。但是得到一个运行时错误 System.Data.dll中发生“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理 其他信息:“=”附近的语法不正确。“ 因此,您的代码必须如下所示:C# 在SqlCommand查询中传递值时出错,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我做错了什么?我只需要一个动态方法,它可以根据值对任何列进行计数。但是得到一个运行时错误 System.Data.dll中发生“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理 其他信息:“=”附近的语法不正确。“ 因此,您的代码必须如下所示: string sqlQuery ="Select Count("+columName+") from tblAttendance1 where "+columName+"='"+value+"'";
string sqlQuery ="Select Count("+columName+") from tblAttendance1 where "+columName+"='"+value+"'";
这里的问题是,
中的“+columName+”='“+value+””
但是更大的问题是,您的命令暴露于SQL注入。要防止这种情况,请使用参数化查询
按以下方式更改它
public static string CountTblColumByValue(string columnName, string value)
{
String cs = ConfigurationManager.ConnectionStrings["BD_CompanyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery ="Select Count(@myColumName) from tblAttendance1 where @myColumName = @myValue ";
using(SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
con.Open();
cmd.Parameters.AddWithValue("@myColumName", columnName);
cmd.Parameters.AddWithValue("@myValue", value);
object count = cmd.ExecuteScalar();
return count.ToString();
}
}
}
代码中的基本错误是
where
和=
之间缺少空格
此外,您应该按照其他答案中的建议,明确地修复SqlInjection
。(但不能对列名使用参数)
之后,您还应该看到,根据Count
定义,您将只获得Count
的notnull
值
Count()
另请参见您将如何实现以下目标:
string sqlQuery ="Select Count("+columName+") from tblAttendance1 where "+columName+"='"+value+"'";
1) 仅计数null
值
2) 计算所有非空值
3) 计数编号/日期操作,即
,之间的
如果代码中不需要这些场景,那么就可以在sql中找到错误的答案 错误很明显,该查询很容易受到SQL注入攻击和转换错误。想象一下,如果将无效字符作为名称或空格传递,会发生什么情况。或者如果恶意用户编写了”;删除表用户--文本框中的code>。错误:where
后缺少空格。大错误:这些易于SQL注入的查询类型使用类似于EF的ORM并使用LINQ创建查询,例如var count=myContext.attention.Where(att=>att.Whatever=someValue.count()
或Where(…).Select(att=>att.SomeColumn).Distinct().Count()
etcIt不是唯一可以破坏此类查询的恶意输入。当您传递日期或小数点时会发生什么?该值将使用用户的区域设置转换为字符串,该区域设置可能不同于服务器的区域设置,并导致服务器以错误的方式解析字符串。不幸的是,您不能对表名或列名使用参数-仅对值使用参数。这个代码不起作用…谢谢你澄清这一点。也许我回答得太多了。简化答案@shezan zahid
public static string CountTblColumByValue(string columnName, string value)
{
String cs = ConfigurationManager.ConnectionStrings["BD_CompanyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery ="Select Count(@myColumName) from tblAttendance1 where @myColumName = @myValue ";
using(SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
con.Open();
cmd.Parameters.AddWithValue("@myColumName", columnName);
cmd.Parameters.AddWithValue("@myValue", value);
object count = cmd.ExecuteScalar();
return count.ToString();
}
}
}