SQL - SQLite - Python - 結合と複数テーブル操作 - みんなでうまくやれないの? - 事前移入
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 8章(結合と複数テーブル操作 - みんなでうまくやれないの?)、p.351(エクササイズ)の解答を求めてみる。
schema4.sql
create table profession (
id integer primary key autoincrement,
profession text
);
insert into profession(
profession
) select profession from my_contacts
group by profession
order by profession;
コード
sample4.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
def p(cur: sqlite3.Cursor, table: str):
cur.execute(
f"""
select * from {table}
"""
)
if (d := cur.description) is not None:
print([t[0] for t in d])
for row in cur.fetchall():
print(row)
p(cur, 'my_contacts')
with open('schema4.sql') as f:
cur.executescript(f.read())
con.commit()
p(cur, 'profession')
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample4.py
['email', 'birthday', 'first_name', 'last_name', 'interests', 'seeking', 'status', 'profession', 'location', 'gender', 'tel', 'city', 'state', 'interest1', 'interest2', 'interest3', 'interest4']
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', '類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None, None, None, 'カヤック乗り', '', '', '類')
(None, None, None, None, '第4', None, None, None, None, None, None, None, None, '第1', '第2', '第3', '第4')
['id', 'profession']
(1, None)
(2, 'テクニカルライター')
%