計算機科学のブログ

SQL - Python - ALTER文 - 過去の書き換え - テーブル名の変更

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

schema2.sql

drop table if exists projekts;
create table projekts (
    number int,
    descriptionofproj text,
    contractoronjob text
);
insert into projekts values
(1, '家の外壁の塗装', 'マーフィー'),
(2, '台所の改築','バルデス'),
(3, 'フローリングの取り付け', 'ケラー'),
(4, '屋根ふき','ジャクソン');

schema2_0.sql

alter table projekts
rename to project_list;

-- proj_desc
-- date_start
-- date_end
-- cost_esti
-- cont_name
-- cont_tel

コード

sample2.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('schema2.sql') as f:
    cur.executescript(f.read())
con.commit()
p(cur, 'projekts')


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

p(cur, 'project_list')

cur.close()
con.close()

入出力結果(Terminal, Zsh)

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