SQL - Python - ALTER文 - 過去の書き換え - COLUMNの追加
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 5章(ALTER文 - 過去の書き換え)、p.199(自分で考えてみよう)の解答を求めてみる。
schema0.sql
select * from my_contacts;
schema1.sql
alter table my_contacts
add column tel text
after first_name;
コード
sample1.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
def p(cur):
with open('schema0.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)
p(cur)
with open('schema1.sql') as f:
cur.executescript(f.read())
con.commit()
p(cur)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample1.py
['email', 'birthday', 'first_name', 'last_name', 'interests', 'seeking', 'status', 'profession', 'location', 'gender']
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F')
['email', 'birthday', 'first_name', 'last_name', 'interests', 'seeking', 'status', 'profession', 'location', 'gender', 'tel']
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None)
%