Reputation: 17
option 1: in this values are inserted using parameters
string insertstr = "INSERT INTO table_name(eid, eName, Dept) " +
"VALUES(@eid, @eName, @dept)";
SqlCommand cmd = new SqlCommand(insertstr, con);
cmd.Parameters.Add("@eid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text);
cmd.Parameters.Add("@ename", SqlDbType.VarChar, 50).Value = textBox2.Text.ToString();
cmd.Parameters.Add("@dept", SqlDbType.VarChar, 100).Value = textBox3.Text.ToString();
Option 2:
SqlCommand cmd = new SqlCommand("INSERT INTO table_name(eid,eName,Dept) values('"+ textBox1.Text +"','"+ textBox2.Text +"','"+ Textbox3.Text +"'", con);
cmd.ExecuteNonQuery();
Most of the projects i had seen the 1st option... what is the use of passing values using parameters?? any advantages by passing values using parameters?? your suggestion plz..
Upvotes: 1
Views: 133
Reputation: 18743
Several reasons:
'
) to avoid SQL errors or SQL injections (as explained by H-Man2).NumberDecimalSeparator
is equal to the comma ,
and you want to insert a Double
value in your database, you normally have to replace the comma by a point. No need to worry about that with parameters.DateTime
formats neither.Upvotes: 1
Reputation: 103348
You should NEVER use option 2.
This is very bad practise, and very open to SQL Injection.
Always stick with Option 1. This is the best option by far.
Read here for more information on SQL Injection: http://en.wikipedia.org/wiki/SQL_injection
Upvotes: 0
Reputation: 3189
You don't have to care about quoting special characters. If you forget to quote a SQL-Injection attack is possible.
If you use Option 2 and one enters the following into Textbox3
'); DELETE * FROM table_name; --
the following SQL statements are excecuted:
INSERT INTO table_name(eid,eName,Dept) values ('value1','value2','');
DELETE * FROM table_name; -- ')
The second statement deletes every row from table_name
. Instead of a delete statement any possible statement could be inserted there.
Upvotes: 8