在Winforms中替换DataGridView中的参数

am46iovg  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(67)

如何使用command.CommandText属性替换输入参数来防止此代码中的SQL注入?

private void button1_Click(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        SqlCommand command = new SqlCommand();
        StringBuilder sb = new StringBuilder();
        bs.DataSource = dataGridView1.DataSource;
        if (textBox1.Text != "")
        {
            sb.Append("DealClassification LIKE '%@Deal%' ");
            command.Parameters.AddWithValue("@Deal", textBox1.Text);
        }
        if (textBox2.Text != "")
        {
            if (sb.Length > 0) sb.Append(" AND ");
            command.Parameters.AddWithValue("@Trader", textBox2.Text);
            sb.Append("TraderName  LIKE '%@Trader%' ");
        }

        command.CommandText = sb.ToString();
        bs.Filter = command.CommandText.ToString();
        dataGridView1.DataSource = bs;
    }

字符串

dw1jzc5e

dw1jzc5e1#

这是错误的:

sb.Append("DealClassification LIKE '%@Deal%' ");

字符串
单引号内的任何内容都是文本,所以你根本没有使用参数。想想参数和引号在C#代码中是如何工作的。如果你这样做了:

private void DisplayText(string text)
{
    Console.WriteLine("text");
}


你希望text参数的值是display还是只是“text”这个词。希望你能理解是后者,那么SQL为什么要有任何不同呢?
这里有两种选择。你可以在SQL代码中保留通配符,而实际使用参数:

sb.Append("DealClassification LIKE '%' + @Deal + '%' ");


另一个选项是将通配符合并到参数值中:

sb.Append("DealClassification LIKE @Deal ");
command.Parameters.AddWithValue("@Deal", $"%{textBox1.Text}%");

相关问题