C #. Transactions in SQL,

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.