Click here to Skip to main content
15,918,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this approach of code but I want to use parameters instead to prevent sql injection .. how to do that ?

here's my code :

C#
if (cn.State == ConnectionState.Closed) cn.Open();
            cm.Connection = cn;
            if (comboBox3.Enabled == true)
            {
                string searchFor2 = comboBox1.Text;
                string searchFor3 = comboBox2.Text;
                string selectSql = "SELECT " + searchFor2 + ", " + searchFor3 + " FROM itmsparts";
                SqlCommand com = new SqlCommand(selectSql, cn);
                try
                {
                    using (SqlDataReader read1 = com.ExecuteReader())
                    {
                        while (read1.Read())
                        {
                            ListViewItem parent = listView1.Items.Add(read1[0].ToString());
                            parent.SubItems.Add(read1[1].ToString());
                        }
                    }
                }
                finally
                {

                }
            }
Posted

1 solution

Using parametrized query is quite a right idea, and the code shown is not. Please see: http://msdn.microsoft.com/en-us/library/ff648339.aspx[^].

See also my past answers:
EROR IN UPATE in com.ExecuteNonQuery();[^],
hi name is not displaying in name?[^].

The query composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but yes, way more important issue is that it opens the doors to SQL injection. The user can write anything in the UI, including some SQL fragment. Are you getting the idea? This is how: http://xkcd.com/327.

—SA
 
Share this answer
 

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