在MySQL中插入带有事务的多个表 [英] Inserting multiple tables with transaction in mysql
本文介绍了在MySQL中插入带有事务的多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要插入两个表
A(id,firstName, lastName)
和
B(id, id from A, xyz)
.
如何使用事务同时同时插入两个表?
How can I insert the two tables simultaneously using transaction?
如果还没有插入B,那么也要回滚A.你能帮我吗?
And also if B is not inserted then rollback the A also. Could you please help me.
推荐答案
如果沿着那条路走,请使用mysql_insert_id().
Use mysql_insert_id() if you're going down that path.
<?
mysql_query("START TRANSACTION");
$q1 = mysql_query("INSERT INTO table A (id, firstName, lastName) VALUES (?, ?, ?)");
// This is your baby. The id of the last record inserted
$last_inserted_id = mysql_insert_id();
$q2 = mysql_query("INSERT INTO table b (id, id from A, xyz) VALUES (?, ?, ?)");
// If query1 and query2 succeeded, commit changes to your database
// Creates both records
if ($q1 && $q2) {
mysql_query("COMMIT");
}
else {
// Else initiate a rollback, and no records are committed.
mysql_query("ROLLBACK");
}
?>
这篇关于在MySQL中插入带有事务的多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文