LoginSignup
2
2

More than 5 years have passed since last update.

スプレッドシートでCSV吐き出して小さなDBのテストデータを作ると結構楽だった

Posted at

テーブル10コぐらいの小さなWebアプリとかを作るとき、そういえばExcelで作って読み込めないかとおもったら、意外と簡単にできたのでメモ。

MySQLでaplicationっていうdb作ってやります。

テーブル

例えば以下の様なテーブル。

create table if not exists users (
    id serial not null primary key,
    email varchar(255) not null,
    name varchar(255) not null,
    password varchar(255) not null,
    created datetime not null default now()
) engine=innodb;

CSV

こんなCSVをエクセルで作ります。
エクセルなら一瞬でできます。

users.csv
1,test1@example1.com,testname1,password1
2,test2@example2.com,testname2,password2
3,test3@example3.com,testname3,password3
4,test4@example4.com,testname4,password4

(passwordはふつうhashですよね)

insert

$ mysql -u root application --local-infile=1
mysql > load data local infile './users.csv' into table users fields terminated by ','

--local-infile=1がポイント。
これでcsvからデータを読み込めます。

以下の様な、ぶっ壊して作りなおすシェルスクリプトを作っておくと便利で楽しいです。

#!/bin/bash

mysql -u root --execute="drop database application"
mysql -u root --execute="source schema.sql"


mysql -u root --local-infile=1 application --execute="\
    load data local infile './users.csv' into table users fields terminated by ','
"
2
2
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
2
2