多个数据库和事务 [英] Multiple database and transactions

查看:74
本文介绍了多个数据库和事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用两个数据库,我必须开始交易吗?这是正确的还是该代码是错误的?如果我在第二个查询中出错,则调用rollback(),但不幸的是不会回滚第一个查询...

If i use two database, i have to start to transaction? Is this correct, or this code is wrong? If i make a mistake in the second query, then call rollback(), but unfortunately won't roll back the first query...

 $conn_site=mysql_connect("localhost", "us", "ps");
 mysql_select_db("site",$conn_site); 
 $conn_forum=mysql_connect("localhost", "us", "ps");
 mysql_select_db("forum",$conn_forum); 

     function begin() {

         @mysql_query("BEGIN",$conn_site);
         @mysql_query("BEGIN",$conn_forum);
     }
    function commit_reg() {
        @mysql_query("COMMIT",$conn_site);
        @mysql_query("COMMIT",$conn_forum);
    }
    function rollback(){
        @mysql_query("ROLLBACK",$conn_site);
        @mysql_query("ROLLBACK",$conn_forum);
    }
   begin();
    mysql_query("insert into users (....) or rollback();
       mysql_query("insert into forumusers (....) or rollback();
    commit();

推荐答案

那不会蹲下.事务被隔离在单个数据库"中.为了使事务跨多个数据库,您需要所谓的分布式事务管理".执行此操作的标准包括XTA.更多的面向企业的框架,包括Java J2EE,都将这类内容作为标准.

That won't do squat. Transactions are isolated within a single "database". In order to have transactions span across multiple databases, you need what's called "distributed transaction management". Standards to do this include XTA. More enterprise oriented frameworks, including Java J2EE, include this sort of thing as standard.

因为看起来您在使用PHP,所以必须自己动手,可以这么说.我假设Mysql支持嵌套事务(我不知道).因此,如果两个数据库上的内部事务都成功,那么您就很好了……提交两个外部事务.如果内部事务中的任何一个失败,请回滚两个外部事务.

Since it looks like you're using PHP, you're going to have to roll your own, so to speak. I'll assume Mysql supports nested transactions (I don't know). So, if the inner transactions on the two db's both succeed, you're good... commit the two outer transactions. If either of the inner transactions fail, rollback both outer transactions.

这篇关于多个数据库和事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆