LoginSignup
63
82

More than 5 years have passed since last update.

PythonからSQLite3で初めてのデータベース!

Last updated at Posted at 2018-06-21

個人的な備忘録も兼ねて。
基本的な操作に関しては公式ドキュメントの上側に書いてあるものがとてもわかりやすいのでそちらも参照すると良い

この文章の中ではPythonとSQL文がごっちゃになっているので、Pythonには左上にpythonと書いてあります。

pythonから扱うには基本的には

python
import sqlite3
conn = sqlite3.connect('example.sqlite3')
c = conn.cursor()
c.execute('create table persons(id integer, name text, birthday)')

という感じでオブジェクトを作って、
c.execute()のカッコ内にSQL文を突っ込めば動きそう。

閉じ方は

python
conn.commit()
conn.close()

で閉じる。
このconn.commit()をしないとsqlite3でデータベースに加えた変更が保存されないので注意。

SQL文

テーブルを新しく作成する。


create table persons(id integer, name text, birthday)

カッコの中身は(カラム名 カラム型)の組み合わせを並べていて、カラム型に使えるものとしては

カラム型の名前 データ型
text     str
integer      int
real float
numeric binary
none none

がある。カラム型は指定しなくても特には問題ない(noneが初期値として入っている)
型を指定してあったところでなんでも入るけど、その型に変換できるようであれば勝手に変換してくれるらしいので基本的には指定しておいた方が便利かも?

ここにわかりやすく書いてあるのでわからなくなったら参照
(SQLにて使えるデータ型についても記述があります。)

カラムを追加する


alter table persons add column blood_type text

personsのところにテーブル名、blood_type textのところにカラム名とカラム型を入れればよい。

カラム名を列挙する

python
for desc in c.description:
    print(desc[0])

#id
#name
#birthday
#blood_type

データを追加する

一つ追加するとき


insert into persons values (1, '太郎', '1996-01-04','B')

複数追加するとき

python

persons_data = [(2,'二郎','1997-01-04','A'),
                (3,'三郎','1998-01-04',None)]
c.executemany("insert into persons values (?,?,?,?)", persons_data)

となる。

中身を見るとき
やり方は公式によれば3つほどあるけど、どれも同じらしいので2つ書いておく。

  • fetchall()を使うやり方
python
c.execute('select * from persons')
data = c.fetchall()
print(data)

#[(1, '太郎', '1996-01-04','B'),(2,'二郎','1997-01-04','A'),(3,'三郎','1998-01-04',None)]
  • イテレータとして扱う方法
python
for row in c.execute('select * from persons'):
    print(row)

#(1, '太郎', '1996-01-04','B')
#(2,'二郎','1997-01-04','A')
#(3,'三郎','1998-01-04',None)

select文の使い方として、
select * from persons order by nameなどとするとそのカラムにおいて昇順で出てくる。
select * from persons where blood_type='B'とすると太郎のデータだけ取り出すことができる。

63
82
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
63
82