在Winforms中替换DataGridView中的参数

am46iovg  于 2023-11-21  发布在  其他
关注(0)|答案(1)|浏览(250)

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

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. BindingSource bs = new BindingSource();
  4. SqlCommand command = new SqlCommand();
  5. StringBuilder sb = new StringBuilder();
  6. bs.DataSource = dataGridView1.DataSource;
  7. if (textBox1.Text != "")
  8. {
  9. sb.Append("DealClassification LIKE '%@Deal%' ");
  10. command.Parameters.AddWithValue("@Deal", textBox1.Text);
  11. }
  12. if (textBox2.Text != "")
  13. {
  14. if (sb.Length > 0) sb.Append(" AND ");
  15. command.Parameters.AddWithValue("@Trader", textBox2.Text);
  16. sb.Append("TraderName LIKE '%@Trader%' ");
  17. }
  18. command.CommandText = sb.ToString();
  19. bs.Filter = command.CommandText.ToString();
  20. dataGridView1.DataSource = bs;
  21. }

字符串

dw1jzc5e

dw1jzc5e1#

这是错误的:

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

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

  1. private void DisplayText(string text)
  2. {
  3. Console.WriteLine("text");
  4. }


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

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


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

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

展开查看全部

相关问题