这是用于进行搜索的代码
private void button1_Click(object sender, EventArgs e)
{
string connectionString = Tyre.Properties.Settings.Default.Database1ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM table1 where Nom like " + textBox1.Text, conn);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
}
我得到这个错误
System.Data.dll 中发生类型为“System.Data.SqlClient.SqlException”的未处理异常
附加信息:列名称“elie”无效。
那是我的应用程序的一个例子: Click here to see the image
最佳答案
首先,您的代码对 SQL Injection 是完全开放的.您允许用户插入他想要的任何数据,包括
; DROP TABLE table1
要解决眼前的问题,请将要匹配的项目用单引号和 % 符号括起来:
"SELECT * FROM table1 where Nom like '%" + textBox1.Text + "%'"
但是,您绝对应该考虑使用 parameterized query .
关于c# - C#如何在数据库中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695282/