我需要一些技巧来更好地做到这一点,我正在使用一个连接插入多个查询。
我知道这 不是一个好的编程 ,尤其是它很容易进行sql注入,我还想提一提它不会在本地运行的Internet上发布。
这是我到目前为止所拥有的..
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(); }
您应该参数化您的查询 -ALWAYS ,但是现在您可以将那些查询与串联;,然后执行一次,如下所示:
;
string allQueries = string.join(';', query2, query3, query4, query5); command.CommandText = allQueries; int c = command.ExecuteNonQuery();
当前,您只在执行一个查询。分号;在SQL中标记语句的结尾,因此将这些语句与组合在一起;将使它们成为独立的语句,但是它们将在一次执行中执行。
kcray-这对我有用。
string[] arr = { query2, query3 }; string allQueries = string.Join(";", arr); command.CommandText = allQueries; int c = command.ExecuteNonQuery();