2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLite3の基本操作

Last updated at Posted at 2020-12-19

軽量なデータベースで、サーバーとしてではなくアプリケーションに組み込んで利用。(スマホアプリなどにも利用される)

**『1データベース、1ファイル』**で扱いやすい。ファイルをコピーすればバックアップが取れるし、削除すれば消える。

ちょっとしたアプリケーションを作る場合に便利なので基本操作をまとめておく。


インストール

https://www.sqlite.org/download.html
Download > Precompiled Binaries for Windows > sqlite-tools-win32-x86-3340000.zip
からダウンロードしてsqlite3.exeを任意の場所に保存。

バージョン確認

sqlite3 --version

起動方法

sqlite3 mydb.db

ファイルが存在すれば開くし、なければ新規作成(ファイルはDBを更新した段階で作成される)

テーブル一覧の確認

.tables

SQLiteのシステムコマンドはドット( . )から始まる。SQLと異なりシステムコマンドの末尾にセミコロン( ; )は不要。

カラムの確認

.schema [table name]

.schema だけだと全テーブルのカラムを表示

Data type Description
integer 整数型
real 浮動小数点型
text 文字列型
blob 無制限スカラ型(画像データなど)
null 格納されたデータに応じて自動的に決定

ただし、他のDBとの互換性向上のため型の表記はゆるめ。

こういった表現でもcreate tableすることができる。
(例)int, tinyint, double, varchar(255)

SQLiteの終了方法

.exit もしくは ctrl + C で終了。

システムコマンド一覧

 .help

外部ファイルの扱い方

SQLファイルの読み込み

  • SQLite起動時に読み込む場合

sqlite3 mydb.b < sample.sql

  • SQLite起動後に読み込む場合

.read sample.sql

SQLファイルのコメント

--コメント もしくは /* コメント */

サンプルデータ

sample.sql
create table if not exists sample_table (id integer primary key autoincrement, name text, col text);

insert into sample_table (name, col) values ('aaa', '111');
insert into sample_table (name, col) values ('bbb', '222');
insert into sample_table (name, col) values ('ccc', '333');
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?