MySQL 多插入? INSERT 失败后 MySQL 数据库完整性
是否可以同时向多个表中插入一行?如果你做几个表通过一个ID关联起来;在 INSERT 失败的情况下确保保持完整性的最佳方法是什么?
Is it possible to insert a row into multiple tables at once? If you do several tables related by an ID; what is the best way to ensure integrity is maintained in case an INSERT fails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这正是事务的用途。如果任何命令失败,则自
START TRANSACTION
起的整个事情都会回滚:这是 MySQL,您不能将事务与 MyISAM 表一起使用(您需要这些表来使用支持某些引擎的引擎)这个,可能是 InnoDB)。
这永远不会被插入到表中(通常您会有一些分支,例如 IF):
警告:更改数据库结构的 SQL 命令结构(例如
CREATE
,< code>ALTER,DROP
) 无法回滚!That's exactly what transactions are for. If any of the commands fail, the whole thing since
START TRANSACTION
is rolled back:This being MySQL, you can't use transactions with MyISAM tables (you'll need the tables to use some engine that supports this, probably InnoDB).
This will never be inserted into the table (normally you'd have some branching, e.g. an IF):
Caveat: SQL commands which change the database structure (e.g.
CREATE
,ALTER
,DROP
) cannot be rolled back!使用交易,卢克。
Use transactions, luke.
MySQL 可以插入多行(搜索“多行” )像这样:
但是,除了查询返回记录、重复项和警告的计数之外,无法判断插入的内容和未插入的内容。您也无法使用
last_insert_id()
来计算新行的 ID,因为它仅返回创建的最后一个 id,而不是一组 id。如果需要保证完整性,请使用单行插入语句和事务。
MySQL can insert multiple rows (search for 'multiple rows') like this:
However, there's no way to tell what got inserted and what wasn't due to constraint violations, beyond the query returning a count of records, duplicates, and warnings. You also can't use
last_insert_id()
to figure out the IDs of the new rows, as that only returns the LAST id that was created, not a set of ids.If you need to guarantee integrity, then use single row insert statements and transactions.