I am using asp.net 4 and visual studio 2010 with ms-sql server 2008 express. I have used three different ways to insert data into a database table:
Way 1:
DataSet dsTab = new DataSet("Table1");
SqlDataAdapter adp = new SqlDataAdapter("Select * from Table1", con);
adp.Fill(dsTab, "Table1");
DataRow dr = dsTab.Tables["Table1"].NewRow();
dr["col1"] = txtBox1.Text;
dr["col2"] = txtBox5.Text;
dr["col3"] = User.Identity.Name.ToString();
dr["col4"] = "text";
dr["col5"] = DateTime.Now;
dr["col6"] = txtBox3.Text;
dr["col7"] = txtBox2.Text;
dsTab.Tables["Table1"].Rows.Add(dr);
SqlCommandBuilder projectBuilder = new SqlCommandBuilder(adp);
DataSet newSet = dsTab.GetChanges(DataRowState.Added);
adp.Update(newSet, "Table1");
Way 2:
SqlDataAdapter AdapterMessage = new SqlDataAdapter();
AdapterMessage.InsertCommand = new SqlCommand();
AdapterMessage.InsertCommand.Connection = con;
AdapterMessage.InsertCommand.CommandText = "insert into Table1(col1,col2,col3,col4,col5,col6,col7) values ('" + txtBox1.Text + "','" + txtBox5.Text + "','" + User.Identity.Name.ToString(); + "','text','" + DateTime.Now + "','" + txtBox3.Text + "','" + txtBox2.Text + "')";
AdapterMessage.InsertCommand.ExecuteNonQuery();
AdapterMessage.Dispose();
Way 3:
string query = "insert into Table1(col1,col2,col3,col4,col5,col6,col7) values ('" + txtBox1.Text + "','" + txtBox5.Text + "','" + User.Identity.Name.ToString(); + "','text','" + DateTime.Now + "','" + txtBox3.Text + "','" + txtBox2.Text + "')";
int i;
SqlCommand cmd = new SqlCommand(query);
con.open();
i = cmd.ExecuteNonQuery();
con.close();
Which among the three is the most optimized way for usage in a website??
The only example you have shown that is NOT vulnerable to a SQL Injection attack is #1.
Since the other two are vulnerable, #1 is your only option (of the three you’ve presented). Go back through your code and fix any examples of #2 or #3 immediately. If you don’t your site will get hacked.
Have you seen performance problems between the various ways you have tried? If not you would be significantly better off spending your time securing your website rather than over-engineering your code.
Take a look at the SqlParameter class. This is the proper way to submit a parametrized query to SQL Server and eliminates the possibility of SQL Injection attacks when used properly.
That said if this were my code I would not use any of those options. Here is the pseudocode for what seems like the best way to me: