Transaction Control for addition, deletion, and modification across databases in C #

Source: Internet
Author: User

During program development, transactions are usually used to add, delete, and modify databases for all updates and rollback. A single database is relatively easy to do. If you need to operate multiple databases at the same time, you can use the following method

I. TransactionScope class

The TransactionScope class is a new class in framework2.0. in the Transactions namespace, you must first add System. transactions references. In addition, you need to go to the windows Control Panel and choose management tools> services> Distributed Transaction Coordinator> Properties> start to start the service. the sample code is as follows:

 

Code
Try
{
Using (TransactionScope scope = new TransactionScope ())
{
// Update the Employees table of the northwind database
Using (SqlConnection conOne = new SqlConnection ("server =.; uid = sa; pwd = 123; database = northwind "))
{
ConOne. Open ();

SqlCommand command = new SqlCommand ("update Employees set lastname = chen where employeeid = 1", conOne );
Int I = command. ExecuteNonQuery ();
}

// Update the jobs table of the pubs Database
Using (SqlConnection conTwo = new SqlConnection ("server =.; uid = sa; pwd = 123; database = pubs "))
{
ConTwo. Open ();
SqlCommand command = new SqlCommand ("update jobs set job_desc = chen where job_id = 1", conTwo );
Int I = command. ExecuteNonQuery ();
}

Scope. Complete (); // submit a transaction
}
}
Catch (Exception ex) // automatically rolls back when an Exception occurs
 

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.