2014年7月15日火曜日

開発環境

Head First SQL ―頭とからだで覚えるSQLの基本 (Lynn Beighley(著)、 佐藤 直生 (監訳)、 松永 多苗子 (翻訳)、オライリージャパン)の1章(データとテーブル: あらゆるものにふさわしい場所)、自分で考えてみよう(p.39)を解いてみる。

自分で考えてみよう(p.39)

コード(BBEdit, Emacs)

sample39.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import sqlite3
import sys
connection = sqlite3.connect('gregs_list.sqlite')
cursor = connection.cursor()

# 列と値の数が異なっている。locationの値がない。
try:
    cursor.execute(
"""
INSERT INTO my_contacts(
last_name, first_name, email, gender, birthday, profession, location, status,
interests, seeking) VALUES (
'アンダーソン', 'ジリアン', 'jill_anderson@breakneckpizza.com', 'F',
'1980-09-05', 'テクニカルライター', '独身', 'カヤック乗り、爬虫類', 'seeking')
"""
)
except Exception:
    print(sys.exc_info())

# 列と値の数が異なっている。列emailがない。
try:
    cursor.execute(
"""
INSERT INTO my_contacts (
last_name, first_name, gender, birthday, profession, location, status,
interests, seeking) VALUES (
'last', 'first', 'xxx@example.com', 'F', '1980-09-05', 'pro', 'loc', 's',
'interests', 'seeking')
"""
)
except Exception:
    print(sys.exc_info())

# professionの値(テクニカルライター)とlocationの値(カリフォルニア州パロアルト)の
# 間にカンマ(,)がない
try:
    cursor.execute(
"""
INSERT INTO my_contacts(
last_name, first_name, email, gender, birthday, profession, location, status,
interests, seeking) VALUES (
'last', 'first', 'email', 'F', '1980-09-05', 'pro' 'loc', 's', 'i', 's')
"""
)
except Exception:
    print(sys.exc_info())

# seekingの値(恋人、友達)がシングルクォートで括られていない
try:
    cursor.execute(
"""
INSERT INTO my_contacts(
last_name, first, email, gender, birthday, profession, location, status,
interests, seeking) VALUES (
'last', 'first', 'email', 'F', '1980-09-05', 'pro', 'loc', 's', 'i',
'恋人、友達)
"""
)
except Exception:
    print(sys.exc_info())

cursor.execute("""SELECT * FROM my_contacts""")
print(cursor.fetchall())

connection.close()

入出力結果(Terminal, IPython)

$ ./sample39.py
(<class 'sqlite3.OperationalError'>, OperationalError('9 values for 10 columns',), <traceback object at 0x102835408>)
(<class 'sqlite3.OperationalError'>, OperationalError('10 values for 9 columns',), <traceback object at 0x102835408>)
(<class 'sqlite3.OperationalError'>, OperationalError('near "\'loc\'": syntax error',), <traceback object at 0x102835408>)
(<class 'sqlite3.OperationalError'>, OperationalError('unrecognized token: "\'恋人、友達)\n"',), <traceback object at 0x102835408>)
[('jill_anderson@breakneckpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F')]
$

0 コメント:

コメントを投稿