LoginSignup
2
6

More than 1 year has passed since last update.

PythonでSQLite3を扱ってみる[備忘録]

Last updated at Posted at 2020-07-31

初めに

sqlitePythonに標準で入っているモジュール。インストールせずにimportできる。

コネクトする

import sqlite3

db = "./exsample.db" # データベースまでのパス
con = sqlite3.connect(db) # コネクト

テーブルを作る

cur = con.cursor()
table = "Friend" # テーブル名
sql = f"""create table {table}(
    id integer primary key autoincrement,
    name text,
    age integer,
)"""
cur.execute(sql) # SQL実行
self.con.commit() # 保存

idprimary keyで主キーにし、autoincrementで自動で振り分けるようにしている。

テーブルがなかったら作る。

table = "Friend" # テーブル名
sql = f"""create table if not exists {table}(
    id integer primary key autoincrement,
    name text,
    age integer,
)"""
cur.execute(sql) # SQL実行
self.con.commit() # 保存

if not existsを入れる。

テーブル編集

old_table = "Friend" # 古いテーブル名
new_table = "NewFriend" # 新しいテーブル名
sql = f"alter table {old_table} rename to {new_table}"
cur.execute(sql) # SQL実行
self.con.commit() # 保存

テーブル削除

table = "NewFriend" # 削除したいテーブル
sql = f"drop table {table}"
cur.execute(sql) # SQL実行
self.con.commit() # 保存

型一覧

型名 情報
NULL NULL値
INTEGER 符号付整数。1, 2, 3, 4, 6, or 8 バイトで格納
REAL 浮動小数点数。8バイトで格納
TEXT テキスト。UTF-8, UTF-16BE or UTF-16-LEのいずれかで格納
BLOB 入力データをそのまま格納

レコード挿入

table = "Friend" # テーブル名
sql = f"insert into {table} (name, age) values ('次郎', 20)"
cur.execute(sql) # SQL実行
self.con.commit() # 保存

又は、

table = "Friend" # テーブル名
sql = f"insert into {table} (name, age) values (?, ?)"
data = ("次郎", 20)
cur.execute(sql, data) # SQL実行
self.con.commit() # 保存

?にして、第2引数にタプルを入れることで挿入できる。

レコード編集

次郎を太郎に変換してみる

table = "Friend" # テーブル名
id = 1 # 編集したいレコードのid
sql = f"update {table} set name='太郎' where id={id}"
cur.execute(sql) # SQL実行
self.con.commit() # 保存

レコード削除

table = "Friend" # テーブル名
id = 1 # 削除するレコードのid
sql = f"delete from {table} where id={id}"
cur.execute(sql) # SQL実行
self.con.commit() # 保存
2
6
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
6