SQL - Python - SELECT文 - 天賦のデータ検索 - WHERE句、AND
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 2章(SELECT文 - 天賦のデータ検索)、p.81(エクササイズ)の解答を求めてみる。
schema6_1.sql
select email from my_contacts
where
profession = 'コンピュータプログラマ';
schema6_2.sql
select last_name, first_name from my_contacts
where
birthday = '1970-04-01';
schema6_3.sql
select last_name, first_name, email from my_contacts
where
location = 'ニュージャージー州グローバーズミル(Grover\s Mill)'
and status = '独身'
and gender = 'M';
schema6_4.sql
select last_name, first_name from my_contacts
where location = 'サンフランシスコ'
and first_name = 'アン';
コード
sample6.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample1.db')
cur = con.cursor()
for i in range(1, 5):
with open(f'schema6_{i}.sql') as f:
cur.execute(f.read())
print([t[0] for t in cur.description])
for row in cur.fetchall():
print(row)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample6.py
['email']
['last_name', 'first_name']
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
('スティーブ', 'ファンヤヨ')
['last_name', 'first_name', 'email']
('スティーブ', 'ファンヤヨ', 'steve@onionflavoredrings.com')
('スティーブ', 'ファンヤヨ', 'steve@onionflavoredrings.com')
('スティーブ', 'ファンヤヨ', 'steve@onionflavoredrings.com')
('スティーブ', 'ファンヤヨ', 'steve@onionflavoredrings.com')
['last_name', 'first_name']
%