您发现了SQL Injection Attacks。根据您指定的原因,仅将用户提供的数据追加到SQL查询中并不是一种好策略。系统中的任何用户都可以尝试通过注入一些SQL来窃取或破坏您的数据。
链接中描述了处理它的方式,但基本上可以指定参数并让提供的类正确处理数据转义,以便有人通过“Drop Table”时,它将作为数据输入。
下面是CodeBetter.com
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Customers WHERE CustomerID = @CustomerID";
command.Parameters.Add(
new SqlParameter("@CustomerID", SqlDbType.NChar, 5)).Value = customerID;
一个很好的例子,另外,随意使用LINQ到SQL。它将为您处理这个问题,并且从开发人员的角度来看更容易。您可以将数据库拖放到代码中,它将完全映射每个表。然后,您可以在您的代码中正确编写LINQ的SQL语句版本,您将在其中获得代码完成和编译时间检查错误。 This SO question will get you started。
下面是一些简单的LINQ代码,可以让你从数据库中读取一个客户,写他/她的名字在屏幕上,然后更新自己的个性化问候语(从SQL注入的所有安全):
Customer myCustomer = (
from cust in myDatabase.Customers
where cust.CustomerID == userPassedCustomerID
select cust).Single();
Console.WriteLine(myCustomer.FullName);
myCustomer.PersonalizedGreeting = userPassedGreeting;
myDatabase.SubmitChanges();