通過執(zhí)行多條SQL語句實現(xiàn)數(shù)據(jù)庫事務
下面將為您介紹如何執(zhí)行多條SQL語句,實現(xiàn)數(shù)據(jù)庫事務的方法,供您參考,如果您對SQL語句和事務感興趣的話,不妨一看,詳細對您學習SQL大有幫助。
/// <summary>
/// 執(zhí)行多條SQL語句,實現(xiàn)數(shù)據(jù)庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static void ExecuteSqlTran(IList<string> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
string upsql = "update 表 set=123 where id=";//省略其他SET
IList<string> l = new List<string>();
for (int i = 0; i <this.DataList1.Items.Count; i++) { CheckBox c= (CheckBox)this.DataList1.Items[i].FindControl("CheckBox1");
TextBox tb = (TextBox)this.DataList1.Items[i].FindControl("TextBox1");
//下面幾個TextBox省略
if(c.Checked)
{
l.Add("update 表 set='"+tb.Text+"' where id="+ this.DataList1.DataKeys[i].ToString());
}
}
SqlServerHelper.ExecuteSqlTran(l);
}
【編輯推薦】