SQL - Python - ALTER文 - 過去の書き換え - CHANGEがないSQLiteの場合, 列名の変更
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 5章(ALTER文 - 過去の書き換え)、p.210(自分で考えてみよう)の解答を求めてみる。
schema3.sql
alter table project_list rename to temp;
create table project_list(
proj_id integer primary key autoincrement,
descriptionofproj text,
contractoronjob text
);
insert into project_list(
proj_id,
descriptionofproj,
contractoronjob
)
select number, descriptionofproj, contractoronjob
from temp;
drop table temp;
コード
sample3.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('schema3.sql') as f:
cur.executescript(f.read())
con.commit()
p(cur, 'project_list')
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample3.py
['number', 'descriptionofproj', 'contractoronjob']
(1, '家の外壁の塗装', 'マーフィー')
(2, '台所の改築', 'バルデス')
(3, 'フローリングの取り付け', 'ケラー')
(4, '屋根ふき', 'ジャクソン')
['proj_id', 'descriptionofproj', 'contractoronjob']
(1, '家の外壁の塗装', 'マーフィー')
(2, '台所の改築', 'バルデス')
(3, 'フローリングの取り付け', 'ケラー')
(4, '屋根ふき', 'ジャクソン')
%