Python+SQLite入門

Pocket

PythonでSQLiteを使うときの基本中の基本をまとめました。


目次


データベースを作る

import sqlite3
dbname = "mydb.db"
con = sqlite3.connect(dbname)
con.close()

テーブルを作る

テーブルを作ります。
冒頭の部分が上述の「データベースを作る」と同じなので、実は「データベースを作る」は実行不要です。

import sqlite3
dbname = "mydb.db"
con = sqlite3.connect(dbname)
cur = con.cursor()
cur.execute("CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, kanji STRING, height INTEGER, sex INTEGER)")
con.commit()
con.close()

CSVをテーブルにインポートする

import sqlite3
dbname = "mydb.db"
con = sqlite3.connect(dbname)
cur = con.cursor()
sql = "insert into person (kanji, height, sex) values (?, ?, ?)"
fn = "person.csv"
with open(fn) as f:
  text = f.read()
lines = text.strip().splitlines()
for line in lines:
  parts=line.split(",")
  cur.execute(sql, tuple(parts))
con.commit()
con.close()

テーブルを削除する

import sqlite3
dbname = "mydb.db"
con = sqlite3.connect(dbname)
cur = con.cursor()
cur.execute("drop table person")
con.close()

全てを表示する

# ループを使う。
import sqlite3
from contextlib import closing
dbname = "mydb.db"
con = sqlite3.connect(dbname)
cur = con.cursor()
sql = "select * from person"
for row in cur.execute(sql):
  print(row)
# fetchallを使う。
sql = "select * from person"
cur.execute(sql)
print(cur.fetchall())

条件で絞る

sql = "select * from person where height>200 and sex=1"
cur.execute(sql)
r = cur.fetchall()
print(r)
# 結果をタプルにしてカウントする。
print(len(tuple(r)))

カウントと平均を使う

sql = "select sex, count(id), avg(height) from person group by sex"
cur.execute(sql)
r = cur.fetchall()
print(r)

データベースの内容を確認する

sql = "select * from sqlite_master"
cur.execute(sql)
r = cur.fetchall()
print(r)

[ 2021年2月4日 | カテゴリー: Python, デジタル | タグ: , ]

« | »

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

送信してください。


タグ

カテゴリー

最近の投稿

最近のコメント

固定ページ

アーカイブ

stabucky

写真

メタ情報