開発環境
- OS X Mavericks - Apple、たまにFreeBSD 10(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4(プログラミング言語)
- SQLite (RDBMS(Relational Database Management System))
Head First SQL ―頭とからだで覚えるSQLの基本 (Lynn Beighley(著)、 佐藤 直生 (監訳)、 松永 多苗子 (翻訳)、オライリージャパン)の5章(ALTER文: 過去の書き換え)、自分で考えてみよう(p.199)を解いてみる。
自分で考えてみよう(p.199)
コード(BBEdit, Emacs)
sample199.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sqlite3
connection = sqlite3.connect('gregs_list.sqlite')
cursor = connection.cursor()
def p(msg):
print(msg)
for row in cursor.fetchall():
print(row)
def p_all(table):
cursor.execute("""SELECT * FROM {0}""".format(table))
print(tuple(map(lambda header: header[0], cursor.description)))
p(table)
p_all('my_contacts')
cursor.execute("""
ALTER TABLE my_contacts
ADD COLUMN tel VARCHAR(10)
""")
connection.commit()
# MySQL固有のAFTERキーワードを使って挿入する列の位置を指定する場合
# ALTER TABLE my_contacts
# ADD COLUMN tel VARCHAR(10)
# AFTER first_name
p_all('my_contacts')
connection.close()
入出力結果(Terminal, IPython)
$ ./sample199.py
('last_name', 'first_name', 'email', 'gender', 'birthday', 'profession', 'location', 'status', 'interests', 'seeking')
my_contacts
('スティーブ', 'ファンヨン', 'steve@onionflavoredrings.com', 'M', '1970-04-01', 'パンクミュージシャン', "ニュージャージー州グローバーズミル (Grover's Mill)", '独身', '国家の破壊', '同国人、ギタープレイヤー')
('スティーブ', 'ファンヨン', 'steve@onionflavoredrings.com', 'M', '1970-04-01', 'パンクミュージシャン', "ニュージャージー州グローバーズミル (Grover's Mill)", '独身', '国家の破壊', '同国人、ギタープレイヤー')
('last_name', 'first_name', 'email', 'gender', 'birthday', 'profession', 'location', 'status', 'interests', 'seeking', 'tel')
my_contacts
('スティーブ', 'ファンヨン', 'steve@onionflavoredrings.com', 'M', '1970-04-01', 'パンクミュージシャン', "ニュージャージー州グローバーズミル (Grover's Mill)", '独身', '国家の破壊', '同国人、ギタープレイヤー', None)
('スティーブ', 'ファンヨン', 'steve@onionflavoredrings.com', 'M', '1970-04-01', 'パンクミュージシャン', "ニュージャージー州グローバーズミル (Grover's Mill)", '独身', '国家の破壊', '同国人、ギタープレイヤー', None)
$
0 コメント:
コメントを投稿