LoginSignup
1
2

More than 5 years have passed since last update.

Command of SQLite3 on Rails

Last updated at Posted at 2016-08-09

基本

$ sqlite3 -version   # バージョンを表示
$ sqlite3 database.sqlite3   # データベースに接続する(同名ファイルがなければ作成して接続する)

sqlite> .help   -- ヘルプを表示する
sqlite> .show   -- 設定情報を表示する
sqlite> .exit   -- 終了する

sqlite> .tables   -- テーブルの一覧を表示する
sqlite> .schema [table]   -- テーブルのスキーマを表示する

-- CREATE
sqlite> CREATE TABLE table (column_a [type], column_b [type]);  -- テーブルを作成する。型の指定は任意。
sqlite> CREATE INDEX index on table (column);   -- インデックスを追加する

-- ALTER
sqlite> ALTER TABLE table_old RENAME TO table_new;   -- テーブル名を変更する
sqlite> ALTER TABLE table ADD COLUMN column;   -- カラムを追加する

-- Drop
sqlite> DROP TABLE table   -- テーブルを削除する

-- INSERT
sqlite> INSERT INTO table (column_a, column_b) VALUES (value_a, value_b);   -- レコードを挿入する

-- UPDATE
sqlite> UPDATE table SET column_a = value_a WHERE column_b = value_b;   -- レコードを更新する

-- DELETE
sqlite> DELETE FROM table WHERE column = value;   -- レコードを削除する

-- SELECT
sqlite> .header on   -- カラム名も出力するよう設定する
sqlite> SELECT * FROM table;   -- 全てのレコードを取得する
sqlite> SELECT (TYPEOF)column FROM table;   -- 全てのレコードから特定のカラムのみ(型情報を含めて)取得する

-- 特殊な変数
sqlite> SELECT current_time;   -- 12:57:55
sqlite> SELECT current_date;   -- 2016-01-28
sqlite> SELECT current_timestamp;   -- 2016-01-28 13:00:47
sqlite> SELECT ROWID, * FROM table   -- ROWIDは内部的にレコードに付与される連番

-- CSVを取り込む
sqlite> .separator ,   -- 区切り文字を変更する
sqlite> .import file table   -- 指定したファイルのデータをテーブルに挿入する

-- バックアップを取る
sqlite> .output backup.dump   -- 出力先を任意のファイルに指定する
sqlite> .dump [table]  -- テーブルのデータを出力する

-- 復元する
sqlite> .read backup.dump   -- バックアップを元に復元する(同じ名前のテーブルが存在する場合はエラーが発生する)

console

rails c
exit
@tasks = Task.all
@task = Task.find(1)
new_task = Task.new
new_task.content = 'NewTask registered!!'
@tasks = Task.all
1
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
1
2