Multi-database transaction processing: Need to be sophisticated

Source: Internet
Author: User

Ext.: http://www.cnblogs.com/tylerdonet/archive/2009/10/30/1592653.html

It is not a problem to implement transactions in a database, when there are often multiple database cross-transactions in the project, this method uses two sqltransaction to handle transactions in these two databases, and when an update is unsuccessful two is rolled back.

1  Public voidTransactiondebug ()2   {3 4    stringSQL1 =@"Data source=xxxxxx;initial catalog=studb;integrated security=true";5    stringSQL2 =@"Data source=xxxxxx;initial catalog=northwind;integrated security=true";6 7SqlConnection conn1 =NewSqlConnection (SQL1);8SqlConnection conn2 =NewSqlConnection (SQL2);9 Ten    stringSqlUpdate1 ="UPDATE stuinfo SET stuaddress= ' Gangnam ' WHERE stuno= ' s25301 '"; One    stringSqlUpdate2 ="UPDATE Products SET productname= ' Chian ' WHERE productid=1"; A  -  -SqlCommand SC1 =NewSqlCommand (sqlUpdate1, conn1); theSqlCommand SC2 =NewSqlCommand (SqlUpdate2, conn2); -  - conn1. Open (); -SqlTransaction SqlTran1 =conn1. BeginTransaction (); + conn2. Open (); -SqlTransaction sqlTran2 =conn2. BeginTransaction (); +  A    inteffectrow=0; at  -    using(TransactionScope Transcope =NewTransactionScope ()) -    { -     Try -     { -Sc1. Transaction =SqlTran1; inEffectrow + =SC1. ExecuteNonQuery (); -  toSC2. Transaction =sqlTran2; +Effectrow + =SC2. ExecuteNonQuery (); -     } the     Catch(SqlException ex) *     { $ Sqltran1.rollback ();Panax Notoginseng Sqltran2.rollback (); - conn1. Close (); the conn2. Close (); +  A      Throwex; the     } +     if(Effectrow = =2) -     { $ sqltran1.commit (); $ sqltran2.commit (); -     } -     Else the     { - Sqltran1.rollback ();Wuyi Sqltran2.rollback (); the     } -  Wu conn1. Close (); - conn2. Close (); About    } $}

Multi-database transaction processing: Need to be sophisticated

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.