调用存储过程时处理SQL注入的最佳实践
本文关键字:最佳 注入 SQL 存储过程 处理 调用 | 更新日期: 2023-09-27 17:59:31
我继承了正在修复安全漏洞的代码。调用存储过程时,处理SQL注入的最佳做法是什么?
代码类似于:
StringBuilder sql = new StringBuilder("");
sql.Append(string.Format("Sp_MyStoredProc '{0}', {1}, {2}", sessionid, myVar, "0"));
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
{
cn.Open();
using (SqlCommand command = new SqlCommand(sql.ToString(), cn))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 10000;
returnCode = (string)command.ExecuteScalar();
}
}
我只是对常规SQL查询做同样的事情,并使用AddParameter
添加参数,对吗?
Q。处理SQL注入的最佳实践是什么?
A。使用参数化查询
示例:
using (SqlConnection connection = new SqlConnection(connectionString)) { // Create the command and set its properties. SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SalesByCategory"; command.CommandType = CommandType.StoredProcedure; // Add the input parameter and set its properties. SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@CategoryName"; parameter.SqlDbType = SqlDbType.NVarChar; parameter.Direction = ParameterDirection.Input; parameter.Value = categoryName; // Add the parameter to the Parameters collection. command.Parameters.Add(parameter); // Open the connection and execute the reader. connection.Open(); SqlDataReader reader = command.ExecuteReader(); . . . }