简体   繁体   中英

multiple databases transactions: mysql, SQL server and PHP

I am building a code with YII / PHP that speaks to two databases a MYSQL and SQL Server.

There are two operations taking place: Writing to MYSQL and Writing to SQL Server. Is there a way to make them atomic ?

Currently I'm doing the following:

$tran1=...$db->beginTransaction();
.....db1...code

$tran2=$db2->beginTransaction();
........
$tran1->commit();
$tran2->commit();

Wondering if there is a way to make them atomic? Nested transactions won't work as these are two different servers.

Thanks,

R

There is always the risk that you committed one and the other fails and then you're in trouble.

So the only addition I can think of here is first making sure that one of the transactions transaction can be committed first and then taking a shot at the other first. MySQL does not have a function to check the transaction state but SQL server does: XACT_STATE() . This gives you near certainty that the SQL transaction is commitable so you can try out the MySQL one first and still be safe if that should fail.

How I would "optimise" your pseudo code:

$result = $sqlDb->query('SELECT XACT_STATE()');
if ($result == 1)
{
   $mysqlDb->commit();
   $sqlDb->commit();
}
else
   rollback both;

I haven't tried this, so no warranty from my end :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM