c#方法一:
TransactionOptions transactionOption = new TransactionOptions(); //設置事務隔離級別 transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; // 設置事務超時時間為60秒 transactionOption.Timeout = new TimeSpan(0, 0, 60); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOption)) { int id = 0; try {
//do something
scope.Complete(); } catch (Exception ex) { throw ex; } finally { scope.Dispose(); } }
c#方法二: SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Transaction = sqlTransaction;
sqlTransaction.Commit();
try
{
// 利用sqlcommand進行數據操作
...
// 成功提交
sqlTransaction.Commit();
}
catch(Exception ex)
{
// 出錯回滾
sqlTransaction.Rollback();
}
finally
{
cnn.Close();
trans.Dispose();
cnn.Dispose();
}
BEGIN TRANSACTION /*--定義變量,用於累計事務執行過程中的錯誤--*/ DECLARE @errorSum INT SET @errorSum=0 --初始化為0,即無錯誤 /*--轉賬:張三的賬戶少1000元,李四的賬戶多1000元*/ SET @errorSum=@errorSum+@@error --累計是否有錯誤 IF @errorSum<>0 --如果有錯誤 BEGIN print '交易失敗,回滾事務' ROLLBACK TRANSACTION --回滾 END ELSE BEGIN print '交易成功,提交事務,寫入硬盤,永久的保存' COMMIT TRANSACTION --執行修改保存 END GO print '查看轉賬事務後的余額' GO SQL中
參考: http://www.cnblogs.com/Garden-blog/archive/2011/04/21/2023417.html