【问题标题】:Inserting multiple tables with transaction in mysql在mysql中插入多个带有事务的表
【发布时间】:2014-08-13 08:34:20
【问题描述】:

我要插入两张表

A(id,firstName, lastName)B(id, id from A, xyz)

如何使用事务同时插入两个表?

如果没有插入B,那么回滚 A也。你能帮帮我吗?

【问题讨论】:

  • 您可以在 Google 上搜索 mysql Transaction。事务可以有多个语句覆盖多个表。如果事务被回滚,那么在该事务中执行的所有步骤都将被恢复,不需要额外的努力。
  • 即使是在 google 或MySQL docs 上最简单的搜索也会告诉你这一点。如果你连自己都懒得做,你会发现别人也懒得帮你。

标签: mysql transactions sql-insert


【解决方案1】:

如果你要走这条路,请使用 mysql_insert_id()。

<?
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");
}

?>

【讨论】:

  • 谢谢。实际上我想在节点 js 中使用它。我会尝试在 nodejs 中实现这个。非常感谢
猜你喜欢
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
  • 2014-10-05
  • 2023-03-16
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多