从SQL文件导入数据库经常会用到,可能是从mysqldump 的脚本恢复数据库,也可能是数据库迁移。往往这样的SQL文件里包含很多条语句,如果中途某条语句出错将会导致整个导入任务终止。遇到这种情况应该怎样处理呢?
先准备一个演示用的SQL脚本 demo.sql
[sql]
SET NAMES UTF8;
CREATE TABLE cc (
`account_id` mediumint(9) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`account_id`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO cc VALUE(1);
INSERT INTO cc (2);
INSERT INTO cc VALUE(3);
将SQL文件导入到数据库test
[plain]
# cat demo.sql | mysql -u root test
ERROR 1064 (42000) at line 9: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2)' at line 1
报告错误。从提示信息里看到,出错的语句是第9行。检查一下
[plain]
# tail -n +9 demo.sql | head -1
INSERT INTO cc (2);
9 前面的+号表示从文件头部开始计算的第9行。发现一个句法错误。用sed 替换某一行
[plain]
# sed -i '9s/.*/INSERT INTO cc VALUE(2);/' demo.sql
替换完成。接着刚才出错的地方继续导入
[plain]
# tail -n+9 demo.sql | mysql -u root test
看看数据库,数据都在,导入成功
[sql]
mysql> select * from cc;
+------------+
| account_id |
+------------+
| 1 |
| 2 |
| 3 |
+------------+
3 rows in set (0.00 sec)