Skip to main content
 首页 » 编程设计

c#之C#如何在数据库中搜索字符串

2024年02月20日24mengfanrong

这是用于进行搜索的代码

 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 .