C#SQL命令变量vs文字

时间:2013-12-04 21:54:42

标签: c# sql ado.net

我正在编写一个数据库CRUD应用程序,并且在尝试将变量传递给数据库时遇到困难。当我将文字值传递给数据库时,应用程序工作正常,例如下面的代码:

myCommand.CommandText = "Select * From Customers Where CustomerID = 'ALFKI'";

但是,当我尝试从文本框中的文本创建变量时,应用程序将不会执行任何操作。它不会抛出错误,只是闲置。这是我用于变量的代码:

string searcher = Convert.ToString(txtSearch);

...

myCommand.CommandText = "Select * From Customers Where CustomerID = " + "'" + searcher + "'";

我在文本框中尝试了不同的CustomerID。我也尝试重新安排单引号和双引号的使用方式,但无济于事。有人可以帮我这个吗?

由于

**

谢谢Jon Skeet!你的方法很完美。达伦,谢谢你的意见。我将很快刷新参数化的sql语句,感谢给我另一个探索的前沿。

2 个答案:

答案 0 :(得分:4)

你应该做的是使用参数化的sql语句。

试试以下

myCommand.CommandText = "Select * From Customers Where CustomerID = @CustomerId";
myCommand.Parameters.AddWithValue("@CustomerId", searcher);

答案 1 :(得分:1)

这一行

string searcher = Convert.ToString(txtSearch);

可能会将变量searcher设置为System.Windows.Forms.TextBox, Text: Foo

您应该使用text属性

string searcher = txtSearch.Text;

仍然应该以Darren Kopp Suggested为例,并使用参数化查询来解决潜在的SQL注入攻击。它也使引用更容易

相关问题