SQL命令中的参数化查询方法

时间:2018-04-11 13:54:15

标签: c# asp.net sql-server sql-injection parameterized-query

现在我想让它成为一个参数化查询,以便它不易于SQL注入。这是代码:

 string sqlText = "SELECT @EmployeeColumn FROM Test_Attachments WHERE Project_Id = @PID1 AND [Directory] = '" + qAttachment.Directory1.Replace("\\\\" + Root_Directory, "") + "' ";

 try 
 {
     SqlCommand myCommand = new SqlCommand(sqlText, SqlConnection);

     myCommand.Parameters.AddWithValue("EmployeeColumn", Employee_Column);
     myCommand.Parameters.AddWithValue("PID1", Project_ID1");
 }
 .....

如何进行参数化查询?特别是用这种方法。感谢

编辑: 抱歉。我在手机上输入这个,所以它有很多错别字。谢谢!

1 个答案:

答案 0 :(得分:0)

PID1已经参数化,因此您可以使用类似的目录。 SELECT子句中还有另一个问题,AddWithValue无法选择要在SELECT中投影的列,但是您可以对其进行验证(我添加了一个内联所有列的示例,但它应该进一步重构)< / p>

string sqlText = "SELECT {{columnName}} FROM Test_Attachments WHERE Project_Id =@PID1 AND [Directory] = @Directory";

var allowedColumns = new List<string>{"columnA", "columnB"};

if(allowedColumns.Contains(Employee_Column)
{
   sqlText = sqlText.Replace("{{columnName}}", Employee_Column);
} 
else
{
   throw new Exception($"Invalid Column {Employee_Column}");
}

try {
    SqlCommand myCommand = new SqlCommand(sqlText, SqlConnection);

    var directory = qAttachment.Directory1.Replace("\\\\" + Root_Directory, "");

     myCommand.Parameters.AddWithValue("@PID1", Project_ID1);
     myCommand.Parameters.AddwithValue("@Directory", directory);

     ...
}