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

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

问:处理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(); . . . }