開発環境
- 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(著)、 佐藤 直生 (監訳)、 松永 多苗子 (翻訳)、オライリージャパン)の2章(SELECT 文: 天賦のデータ検索)、条件分になってみよう(p.97)を解いてみる。
条件分になってみよう(p.97)
コード(BBEdit, Emacs)
sample97.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sqlite3
connection = sqlite3.connect('drinks.sqlite')
cursor = connection.cursor()
def p(msg):
print(msg)
for row in cursor.fetchall():
print(row)
cursor.execute("""
CREATE TABLE doughnut_ratings(
location VARCHAR(50),
time TIME,
date DATE,
type VARCHAR(50),
rating INT,
comments VARCHAR(100))
""")
for row in [('クリスピーキング', '8:50', '9/27', 'プレーングレーズド', 10,
'ほとんど完璧'),
('スターバズコーヒー', '19:35', '5/24', 'シナモンケーキ', 5,
'固いけど、おいしい'),
('スターバズコーヒー', '19:03', '4/26', 'ジャム', 7,
'ジャムが足りない')]:
cursor.execute("""
INSERT INTO doughnut_ratings VALUES('{0}', '{1}', '{2}', '{3}', {4}, '{5}')
""".format(*row))
cursor.execute("""
INSERT INTO doughnut_ratings VALUES(
'ダンカンズドーナツ', '8:59', '8/25', NULL, 6, '脂っこい')
""")
connection.commit()
cursor.execute("""SELECT * FROM drink_info""")
print(tuple(map(lambda header: header[0], cursor.description)))
p('全て')
s = 'SELECT type FROM doughnut_ratings'
cursor.execute("""
{0} WHERE location = 'クリスピーキング' AND rating <> 6
""".format(s))
p('プレーングレーズド')
cursor.execute("""
{0} WHERE location = 'クリスピーキング' AND rating = 3
""".format(s))
p('無し')
cursor.execute("""
{0} WHERE location = 'スナッピーベーグル' AND rating >= 6
""".format(s))
p('無し')
cursor.execute("""
{0} WHERE location = 'クリスピーキング' OR rating > 5
""".format(s))
p('プレーングレーズド, NULL, ジャム')
cursor.execute("""
{0} WHERE location = 'クリスピーキング' OR rating = 3
""".format(s))
p('プレーングレーズド')
cursor.execute("""
{0} WHERE location = 'クリスピーキング' OR rating = 3
""".format(s))
p('プレーングレーズド')
cursor.execute("""
{0} where location = 'スナッピーベーグル' OR rating = 6
""".format(s))
p('NULL')
connection.close()
入出力結果(Terminal, IPython)
$ ./sample97.py
('drink_name', 'cost', 'carbs', 'color', 'ice', 'calories')
全て
('ブラックソーン', 3, 8.4, '黄', 'Y', 33)
('ブルームーン', 2.5, 3.2, '青', 'Y', 12)
('オーマイゴッシュ', 3.5, 8.6, '橙', 'Y', 35)
('ライムフィズ', 2.5, 5.4, '緑', 'Y', 24)
('キスオンザリップス', 5.5, 42.5, '紫', 'Y', 171)
('ホットゴールド', 3.2, 32.1, '橙', 'N', 135)
('ローンツリー', 3.6, 4.2, '赤', 'Y', 17)
('グレイハウンド', 4, 14, '黄', 'Y', 50)
('インディアンサマー', 2.8, 7.2, '茶', 'N', 30)
('ブルフロッグ', 2.6, 21.5, '黄褐色', 'Y', 80)
('ソーダアンドイット', 3.8, 4.7, '赤', 'N', 19)
プレーングレーズド
('プレーングレーズド',)
無し
無し
プレーングレーズド, NULL, ジャム
('プレーングレーズド',)
('ジャム',)
(None,)
プレーングレーズド
('プレーングレーズド',)
プレーングレーズド
('プレーングレーズド',)
NULL
(None,)
$
0 コメント:
コメントを投稿