計算機科学のブログ

SQL - SQLite - Python - ALTER文 - 過去の書き換え - CHANGEがないSQLiteの場合, 列名の変更, 列の追加

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 5章(ALTER文 - 過去の書き換え)、p.213(エクササイズ)の解答を求めてみる。

schema4.sql

drop table if exists temp;
alter table project_list rename to temp;
create table project_list(
    proj_id integer primary key autoincrement,
    proj_desc text,
    con_name text
);
insert into project_list(
    proj_id,
    proj_desc,
    con_name
)
select proj_id, descriptionofproj, contractoronjob
from temp;
drop table temp;

alter table project_list
add column con_phone text;
alter table project_list
add column start_date date;
alter table project_list
add column est_cost real;

コード

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, 'project_list')

with open('schema4.sql') as f:
    cur.executescript(f.read())
con.commit()

p(cur, 'project_list')

cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample4.py 
['proj_id', 'descriptionofproj', 'contractoronjob']
(1, '家の外壁の塗装', 'マーフィー')
(2, '台所の改築', 'バルデス')
(3, 'フローリングの取り付け', 'ケラー')
(4, '屋根ふき', 'ジャクソン')
['proj_id', 'proj_desc', 'con_name', 'con_phone', 'start_date', 'est_cost']
(1, '家の外壁の塗装', 'マーフィー', None, None, None)
(2, '台所の改築', 'バルデス', None, None, None)
(3, 'フローリングの取り付け', 'ケラー', None, None, None)
(4, '屋根ふき', 'ジャクソン', None, None, None)
%