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 ();
}
}