how to make search of a string in a data base in c#

空扰寡人 提交于 2019-12-20 03:52:11

问题


This is the code that is used to make the search

 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;
    }

and im getting this error

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Invalid column name 'elie'.

thats a exemple of my application :

Click here to see the image

回答1:


First off, your code is wide open to SQL Injection. You allow the user to insert any data he wants including

; DROP TABLE table1

To fix the immediate issue surround the item to be matched with single quotes and % signs:

"SELECT * FROM table1 where Nom like '%" + textBox1.Text + "%'"

However, you absolutely should look into using a parameterized query.



来源:https://stackoverflow.com/questions/14695282/how-to-make-search-of-a-string-in-a-data-base-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!