Can you automatically create a mysqldump file that doesn't enforce foreign key constraints?

你。 提交于 2019-11-27 20:22:31

The mysqldump command included with MySQL since version 4.1.1 by default produces a script that turns off the foreign key checks. The following line is included near the top of the dump file:

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;

The /*!40014 ... */ syntax is a conditional comment that will be executed on MySQL version 4.0.14 and later. The old foreign key checks setting is restored towards the end of the dump file:

/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

Note that the conditional comments are interpreted by the the client (rather than the server). If you load the dump file with a client that doesn't support them, then foreign key checks will not be disabled and you might encounter errors. For best results, I'd suggest loading dump files using the official mysql command line client:

mysql -hserver -uuser -p database < dumpfile.sql

It's also worth noting that if mysqldump is run with the --compact option, then the commands to disable and re-enable the foreign key checks are omitted from the dump file.

Beware. For some reason mysqldump doesn't write the FOREIGN_KEY_CHECKS=0 if the --compact option is used.

Ciao.

If you're using phpMyAdmin when exporting SQL, choose Custom Export Method. Then among the checkbox options, click "Disable foreign key checks". The exported SQL statement will have the disable and enable foreign key checks at the beginning and end of the output file respectively.

It's not "automatic", but you won't have to write the statements yourself for every export.

This may happen if you use --compact as one of your mysqldump command. --compact includes --skip-comments so instead --compact one should use --skip-add-drop-table --skip-add-locks --skip-disable-keys --skip-set-charset

Beware of your MySQL client you use, with the mysql command, no problem. Dumping:

% mysqldump -u ocp6 -pocp6 ocp6 --single-transaction --result-file=dump.sql 

Restoring:

% mysql -u ocp6 -pocp6 ocp6 < dump.sql

Everything's fine.

With the use of another MySQL client (mycli in my situation) to restore the dump-file:

mysql ocp6@:(none)> \. dump.sql
[…]
(1005, 'Can\'t create table `ocp6`.`composition` (errno: 150 "Foreign key constraint is incorrectly formed")')

I assume that mycli do not understand conditional comments.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!