LoginSignup
0
0

More than 5 years have passed since last update.

mysqlでダンプファイルからテーブルとcsvデータを読み込む方法

Posted at

はじめに

すでに出来上がってるデータベースに後から追加したいテーブルがある時が発生したので手順を書いていきたいと思います。

手順

ダンプファイルの読み込み

mysql -u username -p dbname < dump.sql 

usernameは設定しているrootなどの名前
dbnameにデータベースの名前
dump.sqlは追加したいデータのモデルなどの詳細が書かれているもの
をそれぞれ指定


csvの読み込み

mysql LOAD DATA LOCAL infile "sample.csv" into table samples fields terminated by ',';

sample.csvには用意したcsvファイルを
samplesのところには上で読み込んだテーブル名を指定
fields terminatedは,(カンマ)で値を区切っているという定義です。
オプションでoptionally enclosed by '"'をつけると日本語のstringなどの囲い文字の定義ができます。


ここでエラー

ERROR 1148 (42000): The used command is not allowed with this MySQL version

参考
local_infileの設定を定義しなければいけないらしいので設定していく。

mysql -u root -p --local-infile dbname
mysql SHOW VARIABLES LIKE 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+
mysql SET GLOBAL local_infile = 1;

もう一度

mysql LOAD DATA LOCAL infile "sample.csv" into table samples fields terminated by ',';

このような返答が返ってきたらok!!

Query OK, 18 rows affected, 92 warnings (0.06 sec)
Records: 18  Deleted: 0  Skipped: 0  Warnings: 92

無事に新しいテーブルを追加することができました!!

終わりに

色んな記事を回っていたら
rake db:dropをして元のデータを全て消してしまい、復活にかなり時間がかかりました。。
恐るべし

db:drop!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0