I need some tips on how to do this better, I am inserting multiple queries with using one connection.
I understand this is not good programming, especially with it being very prone to sql injection, I also wanted to mention it's not going to be out on the internet just run locally.
This is what I have so far..
public partial class Modify : System.Web.UI.Page { OleDbConnection connection; OleDbCommand command; public void OpenConnection2() { connection = new OleDbConnection(""); command = new OleDbCommand(); connection.Open(); } protected void btnSave_Click1(object sender, EventArgs e) { if (AcctNumList.SelectedValue == "3") { string query2 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name1TxtBox.Text.Replace("'", "''"), Amt1TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); string query3 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name2TxtBox.Text.Replace("'", "''"), Amt2TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); string query4 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name3TxtBox.Text.Replace("'", "''"), Amt3TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); OpenConnection2(); command.Connection = connection; command.CommandText = query2; int c = command.ExecuteNonQuery(); connection.Close(); } if (AcctNumList.SelectedValue == "4") { string query2 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name1TxtBox.Text.Replace("'", "''"), Amt1TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); string query3 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name2TxtBox.Text.Replace("'", "''"), Amt2TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); string query4 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name3TxtBox.Text.Replace("'", "''"), Amt3TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); string query5 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values ('{0}','{1}','{2}','{3}','{4}','{5}')", id, newguid, Name4TxtBox.Text.Replace("'", "''"), Amt4TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString()); OpenConnection2(); command.Connection = connection; command.CommandText = query2; int c = command.ExecuteNonQuery(); connection.Close(); }
DbConnectionsandDbCommandsshould be created and disposed as soon as possible (within ausing(...)) -- theOpenConnection2method should not exist.