計算機科学のブログ

SQL - SQLite - Python - 複数テーブルのデータベース設計 - 現行テーブルからの脱却 - 外部キー, references

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 7章(複数テーブルのデータベース設計 - 現行テーブルからの脱却)、p.307(エクササイズ)の解答を求めてみる。

schema6.sql

create table interests (
    int_id integer primary key autoincrement,
    interest text not null,
    contact_id int not null,
    foreign key (contact_id) references my_contacts (contact_id)
);

コード

sample6.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)


with open(f'schema6.sql') as f:
    cur.execute(f.read())
con.commit()

p(cur, 'interests')

cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample6.py 
['int_id', 'interest', 'contact_id']
%