MYSQL匯入中斷處理過程

us_yunleiwang發表於2013-12-19
從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 | -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)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/23490154/viewspace-1063773/,如需轉載,請註明出處,否則將追究法律責任。

相關文章