getting started: SQLite3 on Python3


背景

  • Web 系の実装を少しくらいは自分でできるように、まずは
    data の保存に必要な DB を Python から扱えるようにします。
    • DB は、手軽な SQLite3 を利用します。

環境準備

  • import sqlite3 は初めから利用可能なので不要。

コード

  • file: example.sqlite3 を作り、読み出す。
    • file が not exist なら create_new_table() を実行する。
    • data の内容はてきとう
from __future__ import absolute_import, division, print_function, unicode_literals

import sys
import os
import sqlite3


def create_new_table( s3f) :

    con = sqlite3.connect( s3f)
    c   = con.cursor()

    sql_str = "create table logs ({} integer, {} integer, {} integer, {} integer, {} integer, {} integer, {} integer, {} integer, {} integer, {} integer, {} integer)".format(
        'user_id', 'pref_code', 'year', 'month', 'day', 'rain_pct', 'w_temp', 'y_steps', 'self_exp', 'result', 'm_expect' )
#   print( sql_str)
    c.execute( sql_str)

    cols    = "({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})".format(
        'user_id', 'pref_code', 'year', 'month', 'day', 'rain_pct', 'w_temp', 'y_steps', 'self_exp', 'result', 'm_expect' )
    sql_str = "insert into logs " + cols + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    c.execute( sql_str, (1, 1, 2019, 4,  6, 10, 12, 0, 90, 90, 0))
    c.execute( sql_str, (1, 1, 2019, 4,  7, 30, 14, 0, 80, 70, 0))
    c.execute( sql_str, (1, 1, 2019, 4,  8, 50, 16, 0, 60, 50, 0))
    c.execute( sql_str, (1, 1, 2019, 4,  9, 70, 18, 0, 50, 30, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 10, 90, 20, 0, 60, 10, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 11, 50, 22, 0, 80, 50, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 12, 10, 20, 0, 90, 90, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 13, 10, 18, 0, 90, 90, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 14, 50, 16, 0, 80, 50, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 15, 90, 14, 0, 60, 10, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 16, 70, 12, 0, 50, 30, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 17, 50, 10, 0, 80, 50, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 18, 30, 12, 0, 80, 70, 0))
    c.execute( sql_str, (1, 1, 2019, 4, 19, 10, 14, 0, 90, 90, 0))

    con.commit()
    con.close()


''' SQLite3 '''
s3f = 'example.sqlite3'

if not os.path.exists( s3f) :
    create_new_table( s3f)

con = sqlite3.connect( s3f)
c   = con.cursor()

c.execute( "select * from logs")

data    = c.fetchall()
for line in data :
    print( line)

con.close()

  • connect() と cursor() は create の後に再度実行する必要があった。

  • 簡単にできたので、手軽に DB R/W の Lib. を作れそう。