2013-02-16 60 views
3

我繼承了代碼,我正在修復安全漏洞。在調用存儲過程時處理SQL注入的最佳做法是什麼?調用存儲過程時處理SQL注入的最佳實踐

的代碼是一樣的東西:

StringBuilder sql = new StringBuilder(""); 

sql.Append(string.Format("Sp_MyStoredProc '{0}', {1}, {2}", sessionid, myVar, "0")); 

lock (_lock) 
{ 
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString())) 
    { 
     connection.Open(); 
     using (SqlCommand command = new SqlCommand(sql.ToString(), connection)) 
     { 
      command.CommandType = CommandType.Text; 
      command.CommandTimeout = 10000; 
      returnCode = (string)command.ExecuteScalar(); 
     } 
    } 
} 

我只是做同樣的事情用一個普通的SQL查詢和使用AddParameter正確添加參數?

+0

那是什麼鎖? – 2013-02-16 01:21:33

+1

什麼也沒有,老蹩腳的代碼,這是沒有任何意義的 – cdub 2013-02-16 01:31:36

回答

9

問:處理SQL注入的最佳做法是什麼?

A.使用parameterised queries

例如:

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