C #. Transactions in SQL,
C # Method 1:
TransactionOptions transactionOption = new TransactionOptions (); // sets the transaction isolation level transactionOption. isolationLevel = System. transactions. isolationLevel. readCommitted; // set the transaction timeout to 60 seconds 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 # Method 2: SqlTransaction sqlTransaction = sqlConnection. BeginTransaction ();
SqlCommand sqlCommand = new SqlCommand ();
SqlCommand. Transaction = sqlTransaction;
SqlTransaction. Commit ();
Try
{
// Use sqlcommand to perform data operations
...
// Submitted successfully
SqlTransaction. Commit ();
}
Catch (Exception ex)
{
// Error rollback
SqlTransaction. Rollback ();
}
Finally
{
Cnn. Close ();
Trans. Dispose ();
Cnn. Dispose ();
}
Begin transaction/* -- defines variables used to accumulate errors during TRANSACTION execution -- */DECLARE @ errorSum int set @ errorSum = 0 -- Initialization is 0, that is, no error/* -- transfer: michael's account is less than 1000 yuan, li Si's account is 1000 yuan more */SET @ errorSum = @ errorSum + @ error -- indicates whether an error exists. IF @ errorSum <> 0 -- IF a BEGIN print error occurs, rollback transaction 'rollback transaction' -- roll back end else begin print' TRANSACTION successful, commit TRANSACTION, write to hard disk, permanently save 'commit transaction' -- execute modification and save end go print' to view the balance after the transfer TRANSACTION 'goSQL
Reference: http://www.cnblogs.com/Garden-blog/archive/2011/04/21/2023417.html