I want to improve my coding skills. How do I write this code with concatenation
string query = "insert into StudentInfo values ('" + textBox1.Text.Trim() + "', '" + Name.Trim() + "', '" + comboBox1.SelectedItem.ToString() + "') ";
SqlCommand command = new SqlCommand(query, cn);
command.ExecuteNonQuery();
-
3\$\begingroup\$ You just did write it with concatenation. \$\endgroup\$200_success– 200_success2016年03月10日 07:56:34 +00:00Commented Mar 10, 2016 at 7:56
-
2\$\begingroup\$ You should never ever do something like this ! Sql injection \$\endgroup\$Heslacher– Heslacher2016年03月10日 07:59:49 +00:00Commented Mar 10, 2016 at 7:59
1 Answer 1
Like I had mentioned in my comment this is vulnerable to sql injection. Assume the user of your application inserts Robert'; DROP TABLE StudentInfo;--
that would result in a query text of "insert into StudentInfo values ('Robert','',''); DROP TABLE StudentInfo;-- ', 'theName', 'theComboboxValue') "
resulting in deleting your database table StudentInfo
which isn't what you want !
The solution to this is using SqlParameter
's which will escape the provided values in a way that this can't happen like so
string query = "insert into StudentInfo values (@first, @second, @third)";
SqlCommand command = new SqlCommand(query, cn);
command.Parameters.AddWithValue("@first", textBox1.Text.Trim());
command.Parameters.AddWithValue("@second", Name.Trim());
command.Parameters.AddWithValue("@third", comboBox1.SelectedItem.ToString());
command.ExecuteNonQuery();
I have named the parameters first
, second
and third
, because I don't know what their meaning is, so you should give them proper names yourself. The @
needs to be at the beginning so that the names can be parsed to the desired parameters.
Naming is very important in programming, so you should always use proper names for anything you do. If you come back in 2 weeks to this piece of code you won't know for what e.g textBox1
or comboBox1
are standing.
-
\$\begingroup\$ FWIW it would need a value of
Robert', '', ''); DROP TABLE StudentInfo;--
intextBox1
so the number of columns match. \$\endgroup\$RobH– RobH2016年03月10日 09:09:16 +00:00Commented Mar 10, 2016 at 9:09 -
\$\begingroup\$ @RobH I assumed that the remaining columns can be null ;-) \$\endgroup\$Heslacher– Heslacher2016年03月10日 09:10:10 +00:00Commented Mar 10, 2016 at 9:10
-
\$\begingroup\$ If you omit the column list (which you shouldn't) you have to specify all columns in the insert. \$\endgroup\$RobH– RobH2016年03月10日 09:28:08 +00:00Commented Mar 10, 2016 at 9:28
-
1\$\begingroup\$ Ok, fixed it. My sql is a little bit rusty. \$\endgroup\$Heslacher– Heslacher2016年03月10日 09:29:02 +00:00Commented Mar 10, 2016 at 9:29