How do I dump MySQL file without Foreign Keys via command line?

落花浮王杯 提交于 2019-11-29 07:22:24
philwinkle

From this SO thread:

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

The mysqldump command included with MySQL 5.0.51 (and according to the change log versions since 4.1.1) does switch off foreign key checks. By default, mysqldump includes the following line at 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 4.0.14 and later. The old foreign key checks setting is restored at the end of the dump file:

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

This is ugly, but I ended up just modifying the schema file to remove the foreign keys.


Dump schema only, no foreign keys

mysqldump -uuser -ppassword --no-data dbname | sed '$!N;s/^\(\s*[^C].*\),\n\s*CONSTRAINT.*FOREIGN KEY.*$/\1/;P;D' | grep -v 'FOREIGN KEY' > dbname_schema_no_fk.sql

sed finds lines that precede foreign key constraint declarations and replaces those lines with themselves, minus the trailing comma. grep excludes the foreign key constraints.

Dump data only, no table creation

mysqldump -uuser -ppassword --no-create-info dbname > dbname_data.sql

Load schema first, then data

$ mysql -uuser -ppassword
> create database foo
> use foo
> source dbname_schema_no_fk.sql
> source dbname_data.sql

Tested with mysqldump Ver 10.13 Distrib 5.6.32-78.1, for Linux (x86_64).

you can use the --init-command flag on a per-session basis:

mysql --init-command="SET SESSION FOREIGN_KEY_CHECKS=0;" ... < dump.sql
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!