您当然需要更好的方式来构建您的查询。 如果没有一定的检查或筛选措施,您不会直接接受用户的输入并将其放入您的查询中。这会将你的应用程序暴露给sql注入。 使用SQL参数。 尝试此链接作为参考:http://www.dotnetperls.com/sqlparameter
例如:
using (SqlCommand command = new SqlCommand("Select * from tableBooks WHERE @Field LIKE @Value", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Field", Textbox1.Text)); // I do not recommend using a textbox and letting the user write anything. You have to limit his choices by the fields in your table. Use a dropdownlist and limit his choices by meaningful fields in your "tableBooks" table.
command.Parameters.Add(new SqlParameter("Value", Textbox2.Text));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//GET YOUR BOOK
}
}
请注意我的意见:
//我不建议用一个文本框,让用户写东西的“关键词” 。你必须根据表中的列来限制他的选择。使用下拉列表并通过来自“tableBooks”表的有意义的选择来限制他的选择。
我不想说的太刻薄..但我肯定会挑在[tag:C#]和[tag:SQL]上打开一本书。你的最终查询将毫无意义。 –
另外你应该查找SQL注入攻击。编写这样的代码会让自己陷入一个很大的失败。 –
使用存储过程来搜索数据。 – Raghubar