SQL - Python - 賢いテーブル設計 - 正規化の理由 - 主キー, primary key, autoincrement
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 4章(賢いテーブル設計 - 正規化の理由)、p.189(エクササイズ)の解答を求めてみる。
schema2.sql
drop table if exists your_table;
create table your_table
(
id integer primary key autoincrement,
first_name text,
last_name text
);
insert into your_table (id, first_name, last_name)
values
(null, 'マルシア','ブレディ');
-- insert into your_table (id, first_name, last_name)
-- values
-- (1, 'ジャン','ブレディ');
insert into your_table
values
(2, 'ボビー', 'ブレディ');
insert into your_table (first_name, last_name)
values ('シンディ', 'ブレイディ');
insert into your_table (id, first_name, last_name)
values (99, 'ピーター', 'ブレイディ');
schema2_0.sql
select * from your_table;
コード
sample2.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
with open('schema2.sql') as f:
cur.executescript(f.read())
con.commit()
for i in range(1):
with open(f'schema2_{i}.sql') as f:
cur.execute(f.read())
if (d := cur.description) is not None:
print([t[0] for t in d])
for row in cur.fetchall():
print(row)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample2.py
['id', 'first_name', 'last_name']
(1, 'マルシア', 'ブレディ')
(2, 'ボビー', 'ブレディ')
(3, 'シンディ', 'ブレイディ')
(99, 'ピーター', 'ブレイディ')
%