通過(guò)執(zhí)行多條SQL語(yǔ)句實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)
下面將為您介紹如何執(zhí)行多條SQL語(yǔ)句,實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)的方法,供您參考,如果您對(duì)SQL語(yǔ)句和事務(wù)感興趣的話,不妨一看,詳細(xì)對(duì)您學(xué)習(xí)SQL大有幫助。
/// <summary>
/// 執(zhí)行多條SQL語(yǔ)句,實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)。
/// </summary>
/// <param name="SQLStringList">多條SQL語(yǔ)句</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");
//下面幾個(gè)TextBox省略
if(c.Checked)
{
l.Add("update 表 set='"+tb.Text+"' where id="+ this.DataList1.DataKeys[i].ToString());
}
}
SqlServerHelper.ExecuteSqlTran(l);
}
【編輯推薦】
存儲(chǔ)過(guò)程優(yōu)化的SQL語(yǔ)句寫法