突っ走り書き

見せるほどのものでは..

MySQLの復習@11日目

CSVファイルから読み込み

load data ifile '[file]' into table [tab] [options];

オプションに指定できるのは下の3つ.


option defalut 意味
fields terminamted by '\t' 区切り文字
lines terminamted by '\n' 改行文字
ignore [n] lines 0 スキップする行

上のやり方だけではうまくできないので工夫が必要.

# (POINT-1) MySQLサーバは下のように起動する
mysql --local-infile=1 -u root -p

# (POINT-2) local をつける
load data local infile '/home/me/input.txt' into table tb
fields terminated ',';

# --local-infile=1 で起動しないとエラー
ERROR 1148 (42000): The used command is not allowed with this MySQL version

# local を付けないとエラー
ERROR 13 (HY000): Can't get stat of '/home/me/input.csv' (Errcode: 13)

CSVファイルへの書き出し

# MySQLサーバの実行ユーザーが書き込み権限をもつ場所にしか
# 出力できないので注意(rootなら/tmpとか)
select * into outfile '/tmp/out.csv'
fields terminated by ',' from tb;

SQLコマンドをファイルから実行する

SQLコマンドをテキストファイルに書き込む.

$ cat sql.txt
use example;
select * from member where age >= 20;

MySQLモニタから呼び出す.

# ~ (= ホーム) 使えて happy!
mysql> source ~/sql.txt
Database changed +----+--------+------+
| id | name   | age  |
+----+--------+------+
|  1 | 佐藤   |   30 |
|  2 | 伊藤   |   25 |
+----+--------+------+
2 rows in set (0.00 sec)

コマンドラインから呼び出す.

$ mysql [db] -u [usr] -p -e [command]

# 実際に実行してみる
$ mysql -u root -p -e "source ~/mem.txt"
Enter password:
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  1 | 佐藤   |   30 |
|  2 | 伊藤   |   25 |
+----+--------+------+

ログを取る

# ログ出力開始
tee log.txt Logging to file 'log.txt'

# ログ出力終了
mysql> notee Outfile disabled.

データベースのバックアップ

# out
$ mysqldump -u root -p [db] > [outfile]
$ mysqldump -u root -p [db] [tb] > [outfile]

# in
$ mysql -u root -p [db] < [infile]
$ mysql -u root -p [db] [tb] < [infile]