如何避免绕过SQL Server注入

时间:2014-09-14 07:58:09

标签: c# sql sql-server-2008 sql-injection

我有以下C#代码:

da = new SqlDataAdapter("select * from employ where name = '" + textBox1.Text + "' and Snumber =  
'" + textBox2.Text + "'", cn);
        da.Fill(dt);
        if(dt.Rows.Count > 0)
        {
            MessageBox.Show("not null");
            dt.Clear();

        }
        else
        {
            MessageBox.Show("is null");

        }

问题:如何避免旁路注射

我使用的是SQL Server 2008(9.0 RTM)

提前致谢

2 个答案:

答案 0 :(得分:3)

使用SqlCommand.Parameters

避免SQL注入
var query = "SELECT * FROM employ WHERE name = @name AND Snumber = @number";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name",  textBox1.Text);
cmd.Parameters.AddWithValue("@number",  textBox2.Text);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
...

答案 1 :(得分:0)

使用参数:

...Where name=@name
cmd.Parameters.AddWithValue("@name", textBox1.Text);

或使用存储过程

例如:

SQL:

CREATE PROC sp_Employ_GetByName
   @name varchar(50)
as
BEGIN
    SELECT * FROM EMPLOY
    WHERE NAME=@name
        AND .....
END

C#:

//connect....
SqlCommand cmd = new SqlCommand("sp_Employ_GetByName", ...your connection...);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name", textBox1.Text);
cmd.Parameters.Add("@....", SqlDbType.NVarChar, 30).Value = ...;

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//.......