我继承了code,我修复的安全漏洞了。什么是用于处理SQL注入,当一个存储过程被称为最佳做法?
在code是这样的:
StringBuilder的SQL =新的StringBuilder();
sql.Append(的String.Format(Sp_MyStoredProc{0},{1},{2},的sessionid,myVar的,0));
锁(_lock)
{
使用(SqlConnection的连接=新的SqlConnection(ConfigurationManager.ConnectionStrings [主。的ToString()))
{
connection.Open();
使用(SqlCommand的命令=新的SqlCommand(sql.ToString(),连接))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 10000;
返回code =(字符串)command.ExecuteScalar();
}
}
}
我只是做同样的事情用一个常规的SQL查询,并使用添加参数 AddParameter
是否正确?
Q值。什么是用于处理SQL注入的最佳实践?
一个。使用参数化
查询例如:
使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
//创建命令,并设置其属性。
SqlCommand的命令=新的SqlCommand();
command.Connection =连接;
command.CommandText =SalesByCategory;
command.CommandType = CommandType.StoredProcedure;
//添加输入参数,并设置其属性。
SqlParameter的参数=新的SqlParameter();
parameter.ParameterName =@CategoryName;
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value =类别名称;
//参数添加到Parameters集合。
command.Parameters.Add(参数);
//打开连接并执行读卡器。
connection.Open();
SqlDataReader的读卡器= Command.ExecuteReader却();
。
。
。
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"));
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();
}
}
}
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();
.
.
.