資料庫交易寫法TransactionScope、SqlTransact
- 2008-04-21
- 23842
- 0
資料庫沒有了交易是很要命的,無法確保資料庫的正確,此篇就是在介紹交易的寫法。
▲在.net 1.x的寫法為
string strConn = "連線字串"; SqlConnection conn = new SqlConnection(strConn); conn.Open(); SqlTransaction tran = con.BeginTrasaction(); try { SqlCommand cmd = new SqlCommand("SQL語法", conn); cmd.Transaction = tran; //做你想做的... //做完以後 tran.Commit(); } catch { tran.Rollback();//發生例外就會滾回去 } finally { conn.Dispose(); }
▲在.net 2.x您還可以這樣寫
記得加入參考: System.Transactions.dll
using (TransactionScope scope = new TransactionScope()) { string strConn = "連線字串"; SqlConnection conn = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand("SQL語法", conn); try { conn.Open(); //做你想做的... //做完以後 scope.Complete(); } //Mission Accomplished! catch (Exception ex) { } //發生例外時,會自動rollback finally { cmd.Dispose(); conn.Close(); conn.Dispose(); } }
▲如果您是使用SqlDataSource的話要這樣寫,因為事件關係所以要分兩段來寫注意別寫錯了
protected void SqlDataSource1_Inserting(object sender, SqlDataSourceCommandEventArgs e) { DbCommand dComm = e.Command;//取得sqlcommand DbConnection conn = dComm.Connection;//取得連線 conn.Open();//開啟連線 DbTransaction tran = conn.BeginTransaction();//宣告交易 dComm.Transaction = tran;//指定交易 }
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e) { if (e.Exception == null)//如果沒有發生例外 { e.Command.Transaction.Commit();//交易確認 } else { e.Command.Transaction.Rollback();//交易滾回 } }
以上三種是demo會用的交易方式,如果還有其他寫法的話還請指教
回應討論