計算機科学のブログ

ほしい物リスト

SQL - SQLite - ALTER文 - 過去の書き換え - 列の追加、テーブル名、列名の変更

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

hooptie.sql

drop table if exists hooptie;
drop table if exists car_table;
create table hooptie(
    color text,
    year int,
    make text,
    mo text,
    howmuch real
);

コード

sample5.py

#! /usr/bin/env python3

import sqlite3

con = sqlite3.connect('temp.db')
cur = con.cursor()

with open('hooptie.sql') as f:
    cur.executescript(f.read())

cur.execute('pragma table_info(hooptie)')
for row in cur.fetchall():
    print(row)

sqls = [
    """
alter table hooptie
rename to car_table
""",
    """
alter table car_table
add column car_id integer
""",
    """
alter table car_table
add column vin text
""",
    """
alter table car_table
rename column mo to model
""",
    """
alter table car_table
rename column howmuch to price
""",
]
for sql in sqls:
    cur.execute(sql)
con.commit()
cur.execute('pragma table_info(car_table)')
for row in cur.fetchall():
    print(row)
cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample5.py
(0, 'color', 'TEXT', 0, None, 0)
(1, 'year', 'INT', 0, None, 0)
(2, 'make', 'TEXT', 0, None, 0)
(3, 'mo', 'TEXT', 0, None, 0)
(4, 'howmuch', 'REAL', 0, None, 0)
(0, 'color', 'TEXT', 0, None, 0)
(1, 'year', 'INT', 0, None, 0)
(2, 'make', 'TEXT', 0, None, 0)
(3, 'model', 'TEXT', 0, None, 0)
(4, 'price', 'REAL', 0, None, 0)
(5, 'car_id', 'INTEGER', 0, None, 0)
(6, 'vin', 'TEXT', 0, None, 0)
%