调用存储过程时处理SQL注入的最佳实践

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 添加参数,对吗?

1个回答

11

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();
    .
    .
    .
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接