計算機科学のブログ

ほしい物リスト

SQL - SQLite - 結合と複数テーブル操作 - みんなでうまくやれないの? - create, insert

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 8章(結合と複数テーブル操作 - みんなでうまくやれないの?)、p.351(エクササイズ - 気楽にやってみよう)の解答を求めてみる。

sample4.sql

drop table if exists profession;
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('gregs_list.db')
cur = con.cursor()


with open('sample4.sql') as f:
    cur.executescript(f.read())

sqls = [
    """
select * from my_contacts
""",
    """
select * from profession
""",
]
for sql in sqls:
    print(sql.strip())
    cur.execute(sql)
    for row in cur.fetchall():
        print(row)

cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample4.py
select * from my_contacts
('アンダーソン', 'ジリアン', 'F', 'jill_anderson@breakneckpizza.com', '1980-09-05', 'テクニカルライター', 'カリフォルニア州パロアルト', '独身', 'カヤック乗り、爬虫類', '恋人、友達', None, None, None, None, None, None, None)
select * from profession
(1, 'テクニカルライター')
%