I have inherited code that I am fixing security holes up. What's the best practice for handling SQL injections when a stored procedure is called?
The code is something like:
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();
}
}
I just do the same thing with a regular SQL query and add the parameters using AddParameter
correct?
Q. What's the Best practice for Handling SQL injections?
A. Use parameterised queries
example:
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(); . . . }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With