4

我继承了正在修复安全漏洞的代码。调用存储过程时处理 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正确的添加参数?

4

1 回答 1

11

问:处理 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();
    .
    .
    .
}
于 2013-02-16T01:22:18.213 回答