.NET開發中的交易處理大比拼

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   sp   strong   

本文轉載:http://www.cnblogs.com/jhxk/articles/2696307.html

              http://liubaolongg.blog.163.com/blog/static/21386802201222631355218/

.NET事務

  • ADO.NET事務
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString)){    conn.Open();    using (SqlTransaction tran = conn.BeginTransaction())    {        using (SqlCommand cmd = new SqlCommand())        {            cmd.Connection = conn;            cmd.CommandType = CommandType.Text;            cmd.Transaction = tran;            try            {                cmd.CommandText = sql1;                cmd.ExecuteNonQuery();                cmd.CommandText = sql2;                cmd.ExecuteNonQuery();                tran.Commit();                Response.Write("Ok");            }            catch (SqlException ex)            {                tran.Rollback();                Response.Write("Error:" + ex.Message);            }        }    }    conn.Close();}     ADO.NET 明確交易佔用資源少、速度快,但功能簡單,只能管理單一對象和單一持久資源間的事務,比如想在資料庫 B 插入失敗,則復原對資料庫 A 的操作,就無法用這種 ADO.NET 明確交易來實現。 
View Code

 

  • 隱含交易(TransactionScope)
隱含交易不具有Commit、Roolback方法。using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString)){    using (TransactionScope ts = new TransactionScope())    {        conn.Open();        using (SqlCommand cmd = new SqlCommand())        {            cmd.Connection = conn;            cmd.CommandType = CommandType.Text;            try            {                cmd.CommandText = "insert into TranTable(Priority) values(1)";                cmd.ExecuteNonQuery();                cmd.CommandText = "insert into TranTable(Priority) values(256)";                cmd.ExecuteNonQuery();                ts.Complete();                Response.Write("Ok");            }            catch (SqlException ex)            {                Response.Write("Error:" + ex.Message);            }        }    }    conn.Close();}     TransactionScope沒有和資料庫直接關聯,那是怎麼實現用事務的方式執行語句的呢?    如果我們在連接字串裡面加上Enlist=false;,再執行上面的代碼,發現插入了一條1的記錄,說明並不是以事務方式執行的。Enlist預設為true,SqlClient會自動檢測是否存在事務,如果有事務,則自動登記到事務中。
View Code

 

  • 顯示事務(CommittableTransaction)
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString)){    using (CommittableTransaction ct = new CommittableTransaction())    {        conn.Open();        conn.EnlistTransaction(ct);//將串連登記到事務        using (SqlCommand cmd = new SqlCommand())        {            cmd.Connection = conn;            cmd.CommandType = CommandType.Text;            try            {                cmd.CommandText = "insert into TranTable(Priority) values(1)";                cmd.ExecuteNonQuery();                cmd.CommandText = "insert into TranTable(Priority) values(256)";                cmd.ExecuteNonQuery();                ct.Commit();                Response.Write("Ok");            }            catch (SqlException ex)            {                ct.Rollback();                Response.Write("Error:" + ex.Message);            }        }    }    conn.Close();}
View Code

 

  • WebService(TransactionOption)
首先引用using System.EnterpriseServices;,然後設定屬性TransactionOption = TransactionOption.Required。設定TransactionOption.Disabled、TransactionOption.NotSupported、TransactionOption.Supported表示不參與事務。設定TransactionOption.Required、TransactionOption.RequiresNew表示建立一個新的事務。意思是說當TransactionOption的屬性為Required或 RequiresNew的WEB服務方法調用另一個TransactionOption的屬性為Required或RequiresNew的WEB服務方法時,每個WEB服務方法將參與他們自己的事務,因為Web Service方法只能用作事務中的根對象。PS:WEB服務方法的TransactionOption預設屬性為Disabled提交事務ContextUtil.SetComplete();復原事務ContextUtil.SetAbort(); [WebMethod(TransactionOption = TransactionOption.Required)]public string HelloWorld(){    try    {        ContextUtil.EnableCommit();//開啟事務        SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=sa;database=db.mdf;");        SqlCommand cmd = new SqlCommand("update users set name = ‘yangxing‘ where id = 5", con);        con.Open();        cmd.ExecuteNonQuery();        cmd.CommandText = "update users1 set name = ‘yangxing1‘ where id = 6";//users1表不存在,執行該語句報錯        cmd.ExecuteNonQuery();//拋出異常        ContextUtil.SetComplete();//提交事務        return "true";    }    catch    {        ContextUtil.SetAbort();//復原事務        return "false";    }} 
View Code
  • 自動交易處理
在方法之前增加屬性[AutoComplete(true)],這樣如果方法執行時沒有異常就預設提交,如果有異常則這個方法就會復原。                                    using System;using System.Data.SqlClient;using System.EnterpriseServices;//企業級服務COM+事務namespace ClassTran{    [Transaction(TransactionOption.Required)]    public class OrderData2 : ServicedComponent    {        //自動事務        [AutoComplete(true)]        public string WorkTran()        {            string msg = "";            string conString = "data source=127.0.0.1;database=codematic;               user id=sa;password=";            SqlConnection myConnection = new SqlConnection(conString);            myConnection.Open();                                               SqlCommand myCommand = new SqlCommand();            myCommand.Connection = myConnection;                       try            {                myCommand.CommandText = "update P_Product set Name=‘電腦2‘                     where Id=52";                myCommand.ExecuteNonQuery();                myCommand.CommandText = "update P_Product set Name=‘電腦3‘                where Id=53";                myCommand.ExecuteNonQuery();                msg ="成功!";            }            catch (Exception ex)            {                msg = "失敗:"+ex.Message;                          }            finally            {                myConnection.Close();            }            return msg;        }    }}
View Code

 

.NET開發中的交易處理大比拼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.