程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net創建事務的方法

asp.net創建事務的方法

編輯:ASP.NET基礎

1、建立List用於存放多條語句

/// <summary>
/// 保存表單
/// </summary>
/// <param name="context"></param>
protected void save()
{
 List<string> list = new List<string>();
 list.Add(string.Format("insert into picsone(model,idser,idflg,lmuser,lmdate,lmtime) values('{0}','{1}','{2}','{3}',{4},{5})", "T1002", "Y", "N", "U001", 20161103, 140025));
 list.Add(string.Format("insert into picstwo(model,idser,idflg,lmuser,lmdate,lmtime) values('{0}','{1}','{2}','{3}',{4},{5})", "T1002", "Y", "N", "U001", 20161103, 140025));
 bool bol = ExecuteTransaction(list);
 if (bol)
 {
  MessageBox.Show("保存成功!");
 }
 else
 {
  MessageBox.Show("保存失敗!");
 }
}

2、調用ExecuteTransaction方法,並返回返回值true為成功,false為失敗,語句並回滾

/// <summary>
/// 執行語句
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
private bool ExecuteTransaction(List<string> list)
{
 using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["LocalConnectionString"].ToString()))
 {
  SqlCommand command = new SqlCommand();
  SqlTransaction transaction = null;
  try
  {
   connection.Open();
   transaction = connection.BeginTransaction();
   command.Connection = connection;
   command.Transaction = transaction;
 
   for (int i = 0; i < list.Count; i++)
   {
    command.CommandText = list[i];
    command.ExecuteNonQuery();
   }
 
   transaction.Commit();
   connection.Close();
   return true;
  }
  catch
  {
   transaction.Rollback();
   connection.Close();
   return false;
  }
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved