開発環境
- 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(著)、 佐藤 直生 (監訳)、 松永 多苗子 (翻訳)、オライリージャパン)の7章(複数テーブルのデータベース設計: 現行テーブルからの脱却)、エクササイズ(p.307)を解いてみる。
エクササイズ(p.307)
コード(BBEdit, Emacs)
sample307.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sqlite3
connection = sqlite3.connect('gregs_list.sqlite')
cursor = connection.cursor()
def p_all(table):
cursor.execute("""SELECT * FROM {0}""".format(table))
print(tuple(map(lambda header: header[0], cursor.description)))
p(table)
def p(msg):
print(msg)
for row in cursor.fetchall():
print(row)
p_all('my_contacts')
cursor.execute("""
CREATE TABLE interests(
int_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
interest VARCHAR(50) NOT NULL,
contact_id INTEGER NOT NULL,
FOREIGN KEY(contact_id) REFERENCES my_contacts(contact_id)
)
""")
p_all('interests')
connection.commit()
connection.close()
入出力結果(Terminal, IPython)
$ ./sample307.py
('contact_id', 'last_name', 'first_name', 'email', 'gender', 'birthday', 'profession', 'location', 'status', 'interests', 'seeking')
my_contacts
('int_id', 'interest', 'contact_id')
interests
$
0 コメント:
コメントを投稿