Maison > Article > développement back-end > 同时操作不同库里表,支持事物吗,mysql解决办法
同时操作不同库里表,支持事物吗,mysql
MYSQL数据库
有数据库A和数据库B,同时操作A中两张表和B中两张表,支持事物回滚么,都是innodb。。
分两种情况
A库和B库在同一台服务器
A库和B库不在同一台服务器
请教大神
------解决思路----------------------
A库和B库在同一台服务器
A库和B库不在同一台服务器
两个都支持事务。
可以使用分布式事务
<br />public function testAction(){<br /> $goods_id=1;<br /> $goods_name = "大西瓜";<br /> $num = 1;<br /> $rs_order = $this->test->createorder($goods_id,$goods_name,$num);<br /> $rs_goods = $this->test->deduction($goods_id,$num);<br /> if($rs_order['status'] =="success" && $rs_goods['status']=="success"){<br /> $this->test->commitdb($rs_order['XA']);<br /> $this->test->commitdb1($rs_goods['XA']);<br /> }else{<br /> $this->test->rollbackdb($rs_order['XA']);<br /> $this->test->rollbackdb1($rs_goods['XA']);<br /> }<br /> <br /> print_r($rs_order);<br /> echo "<br />";<br /> print_r($rs_goods);<br /> die("dddd");<br /> }<br /> <br /> public function createorder($goods_id,$goods_name,$num){<br /> $XA = uniqid("");<br /> $this->_db->query("XA START '$XA'");<br /> $_rs = true;<br /> try {<br /> $data = array();<br /> $data['order_id'] = "V".date("YmdHis");<br /> $data['goods_name'] = $goods_name;<br /> $data['goods_num'] = $num;<br /> $this->_db->insert("temp_orders",$data);<br /> $rs = $this->_db->lastInsertId();<br /> if($rs){<br /> $_rs = true;<br /> }else{<br /> $_rs = false;<br /> }<br /> } catch (Exception $e) {<br /> $_rs = false;<br /> }<br /> $this->_db->query("XA END '$XA'");<br /> if($_rs){<br /> $this->_db->query("XA PREPARE '$XA'");<br /> return array("status"=>"success","XA"=>$XA);<br /> }else{<br /> return array("status"=>"nosuccess","XA"=>$XA);<br /> }<br /> }<br /> <br /> public function deduction($id){<br /> $XA = uniqid("");<br /> $this->db1->query("XA START '$XA'");<br /> $last_rs = true;<br /> try {<br /> $sql = "select * from temp_goods where id = '$id' and goods_num>0";<br /> $rs = $this->db1->fetchRow($sql);<br /> if(!empty($rs)){<br /> $sql = "update temp_goods set goods_num = goods_num-1 where id = '$id'";<br /> $rd = $this->db1->query($sql);<br /> if($rd){<br /> $last_rs = true;<br /> }else{<br /> $last_rs = false;<br /> }<br /> }else{<br /> $last_rs = false;;<br /> }<br /> } catch (Exception $e) {<br /> $last_rs = false;;<br /> }<br /> $this->db1->query("XA END '$XA'");<br /> <br /> if($last_rs){<br /> $this->db1->query("XA PREPARE '$XA'");<br /> return array("status"=>"success","XA"=>$XA);<br /> }else{<br /> return array("status"=>"nosuccess","XA"=>$XA);<br /> }<br /> <br /> }<br /> //提交事务!<br /> public function commitdb($xa){<br /> return $this->_db->query("XA COMMIT '$xa'");<br /> }<br /> <br /> //回滚事务<br /> public function rollbackdb($xa){<br /> return $this->_db->query("XA ROLLBACK '$xa'");<br /> }<br /> <br /> //提交事务!<br /> public function commitdb1($xa){<br /> return $this->db1->query("XA COMMIT '$xa'");<br /> }<br /> <br /> //回滚事务<br /> public function rollbackdb1($xa){<br /> return $this->db1->query("XA ROLLBACK '$xa'");<br /> }<br /><br />