Click here to Skip to main content
15,914,163 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi i want to search a name from database using c# But its giving error "Unknown column string". But for integer number this is working.
C#
try
                {
                    con = new MySqlConnection();
                    con.ConnectionString = ConfigurationSettings.AppSettings["constr"];
                    con.Open();
                    string str = "select pfno,name,desig,oldtno,newtno from empreg where name like " + textBox1.Text;
                    da = new MySqlDataAdapter(str, con);
                    ds = new DataSet();
                    da.Fill(ds, "empreg");
                    dataGridView1.DataSource = ds.Tables[1];
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                }
Posted
Updated 6-Aug-12 11:27am
v2
Comments
[no name] 6-Aug-12 17:28pm    
string str = "select pfno,name,desig,oldtno,newtno from empreg where name like '%" + textBox1.Text + "%'"; We will discuss SQL injection attacks another time.
Kenneth Haugland 6-Aug-12 17:29pm    
So whats the value in the Textox then? And does you query work if you hard code it ?
[no name] 6-Aug-12 17:32pm    
You need single quotes around strings. Integers you do not.
Anurag Sarkar 6-Aug-12 17:37pm    
thanks Wes lov u:)

One more useful article on SQL injection:
http://en.wikipedia.org/wiki/SQL_injection[^].

You really need to get rid of building a query string by concatenation with some data taken from the UI. In a nutshell the idea of the exploit if very simple: anything can be placed in textBox1.Text. Even a fragment of SQL code. Parametrized statements solve this problem.

—SA
 
Share this answer
 
"select * from empreg where pfno LIKE '%"+textBox1.Text+"%'";
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Aug-12 18:41pm    
No, no, this is subject to SQL Injection. Never do such things.
--SA
Anurag Sarkar 7-Aug-12 2:48am    
ok as you say sir.
Here is the answer of what Wes wanted to learn you:
SQL Injection Attacks and Some Tips on How to Prevent Them[^]
 
Share this answer
 
Comments
Anurag Sarkar 6-Aug-12 17:39pm    
Thanks
Sergey Alexandrovich Kryukov 6-Aug-12 18:42pm    
My 5. I added my variant of explaining this thing, please see.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900