Multi-Database Transaction Processing [rewrite]

Source: Internet
Author: User
I saw a tall man in the garden write a multi-database transaction, and I thought it was very interesting. I wrote it again.

There is no problem in implementing transactions in a database. At that time, the project often encountered multiple database cross transactions. This method uses two sqltransactions to process the transactions in the two databases, if an update fails, both of them must be rolled back.

Public void transactiondebug ()
{

String sql1 = @ "Data Source = xxxxxx; initial catalog = studb; Integrated Security = true ";
String sql2 = @ "Data Source = xxxxxx; initial catalog = northwind; Integrated Security = true ";

Sqlconnection conn1 = new sqlconnection (sql1 );
Sqlconnection conn2 = new sqlconnection (sql2 );

String sqlupdate1 = "Update stuinfo set stuaddress = 'jiangnan 'Where stuno = 's25301 '";
String sqlupdate2 = "update products set productname = 'chian 'Where productid = 1 ";

Sqlcommand SC1 = new sqlcommand (sqlupdate1, conn1 );
Sqlcommand SC2 = new sqlcommand (sqlupdate2, conn2 );

Conn1.open ();
Sqltransaction sqltran1 = conn1.begintransaction ();
Conn2.open ();
Sqltransaction sqltran2 = conn2.begintransaction ();

Int pair Trow = 0;

Using (transactionscope transcope = new transactionscope ())
{
Try
{
Sc1.transaction = sqltran1;
Repeated Trow + = sc1.executenonquery ();

Sc2.transaction = sqltran2;
Repeated Trow + = sc2.executenonquery ();
}
Catch (sqlexception ex)
{
Sqltran1.rollback ();
Sqltran2.rollback ();
Conn1.close ();
Conn2.close ();

Throw ex;
}
If (export Trow = 2)
{
Sqltran1.commit ();
Sqltran2.commit ();
}
Else
{
Sqltran1.rollback ();
Sqltran2.rollback ();
}

Conn1.close ();
Conn2.close ();
}
}

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.