我有一个Project
表格,包含两列--ProjectId
和ProjectName
--我正在编写一个函数,构建并执行一个SqlCommand
来查询具有给定名称的项目的ID。这个命令可以工作,但容易受到SQL注入的攻击:
string sqlCommand = String.Format("SELECT {0} FROM {1} WHERE {2} = {3}",
attributeParam, tableParam, idParam, surroundWithSingleQuotes(idValue));
SqlCommand command = new SqlCommand(sqlCommand, sqlDbConnection);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
DataTable attributes = new DataTable();
adapter.Fill(attributes);
...
}
attributeParam
、tableParam
、idParam
和idValue
都是字符串,例如:"ProjectId"
、"Project"
、"ProjectName"
和"MyFirstProject"
。 surroundWithSingleQuotes
会使用''
将字符串括起来,因此surroundWithSingleQuotes(idValue) == "'MyFirstProject'"
。我试图尽可能地编写通用的函数,因为我将来可能需要从表中获取给定属性的全部内容。
虽然上面的String.Format可以工作,但这个却不行:
string sqlCommand = String.Format("SELECT @attributeparam FROM {0} WHERE " +
"@idparam = @idvalue", tableParam);
command.Parameters.Add(new SqlParameter("@attributeparam", attributeParam));
command.Parameters.Add(new SqlParameter("@idparam", idParam));
command.Parameters.Add(new SqlParameter("@idvalue",
surroundWithSingleQuotes(idValue)));
SqlCommand command = new SqlCommand(sqlCommand, sqlDbConnection);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
DataTable attributes = new DataTable();
adapter.Fill(attributes);
...
}
我不确定为什么会这样。我没有收到任何错误信息,但是当我使用SqlDataAdapter填充我的DataTable时,DataTable为空。以下是我尝试过的各种方法,但都无济于事:
- 根据此答案和Microsoft文档,使用AddWithValue或使用Parameters.Add和SqlParameter.Value。
- 有选择地替换String.Format中的{0}、{1}、{2}和{3},用实际值或参数字符串替换。
{3}
。 - Scott Chamberlainstring.Format
。 - juharr