SQLite3 を少し使ってみる

[`evernote` not found]
Bookmark this on Hatena Bookmark
Share on Facebook
LINEで送る

接続

1ファイル1DB なので,ファイル名を指定して起動する.

$ sqlite3 DBFILENAME
テーブルリスト,カラムリスト

覚えるしかないか.

テーブルリスト

> .table;

カラムリスト

> pragma table_info(TABLENAME);

カラムリストの要素は順に,

cid         Integer  インデックス
name        Text     カラム名
type        Text     そのカラムの型
notnull     Integer  not null なら 1
dflt_value  Text     DEFAULT value
pk          Integer  プライマリキーなら 1
NULL, INTEGER, REAL, TEXT, BLOB (バイナリーオブジェクト)
日付の取扱

日付関数で文字列か数値に変換して保存する.

例: データが python の datedata=datetime(2004, 10, 1, 13, 20, 15) の時

文字列で保存する例,エポックで保存する例

datestring=datedata.strftime('%Y-%m-%d %H:%M:%S')
connection=sqlite3.connect('filename')
cursor=connection.cursor()
cursor.execute('create table tablename ( str_date text, int_date integer );')
cursor.execute('insert into tablename values (\'%s\', strftime(\'%%s\',\'%s\'));'%(datestring, datestring))
cursor.commit()

格納状態

[(u'2004-10-01 13:20:15', 1096636815)]

値の取り出し方:
以下の取り出し関数を通して取り出す

  • date -- 日付
  • datetime -- 日時
  • time -- 時刻
  • julianday -- ユリウス日
  • strftime -- その他
cursor.execute('select time(str_date),date(int_date,\'unixepoch\') from tablename')

取得結果

[(u'13:20:15', u'2004-10-01')]