Search code examples
c#sqlsql-server-2008sql-injection

how to avoid bypass SQL server injection


I have the following C# code :

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");

        }

QUESTION: How to avoid bypass injection

I'm using SQL Server 2008 (9.0 RTM)

Thanks in advance


Solution

  • Avoid SQL injection by using SqlCommand.Parameters

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