開発環境
- macOS Mojave - Apple
- Emacs (Text Editor)
- PostgreSQL (ORDBMS(object-relational database management system))
- Python 3.7 (プログラミング言語)
- psycopg2(パッケージ)
Head First SQL ―頭とからだで覚えるSQLの基本 (Lynn Beighley (著), 佐藤 直生 (監訳)、松永 多苗子 (翻訳)、オライリージャパン)の2章(SELECT文 - 天賦のデータ検索)、エクササイズ(p. 69).を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3
import psycopg2 as sql
conn = sql.connect(database='gregs_list', user='kamimura')
cursor = conn.cursor()
_sql = '''
insert into my_contacts
(first_name, last_name, email, gender, birthday, profession, location, status,
interests, seeking)
values
(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
'''
cursor.executemany(_sql,
[('スティーブ', 'ファンヨン', 'steve@onionflavoredrings.com',
'M', '1970-04-01', 'パンクミュージシャン',
"ニュージャージー州グローバーズミル (Grover's Mill)", '独身',
'国家の破壊', '同国人、ギタープレイヤー'),
('スティーブ', 'ファンヨン', 'steve@onionflavoredrings.com',
'M', '1970-04-01', 'パンクミュージシャン', "Grover's Mill",
'独身', '国家の破壊', '同国人、ギタープレイヤー')])
conn.commit()
cursor.execute('''select * from my_contacts''')
for row in cursor.fetchall():
print(row)
print()
_sqls = ["select * from my_contacts where location = 'Grover\'s Mill'",
"select * from my_contacts where location = 'Grover''s Mill'"]
for _sql in _sqls:
print(_sql)
try:
cursor.execute(_sql)
for row in cursor.fetchall():
print(row)
print()
except Exception as err:
print(type(err), err)
conn.commit()
cursor.close()
conn.close()
入出力結果(Terminal, Jupyter(IPython))
$ ./sample3.py
('steve@onionflavoredrings.com', datetime.date(1970, 4, 1), 'スティーブ', 'ファンヨン', '国家の破壊', '同国人、ギタープレイヤー', '独身', 'パンクミュージシャン', "ニュージャージー州グローバーズミル (Grover's Mill)", 'M')
('steve@onionflavoredrings.com', datetime.date(1970, 4, 1), 'スティーブ', 'ファンヨン', '国家の破壊', '同国人、ギタープレイヤー', '独身', 'パンクミュージシャン', "Grover's Mill", 'M')
select * from my_contacts where location = 'Grover's Mill'
<class 'psycopg2.ProgrammingError'> syntax error at or near "s"
LINE 1: select * from my_contacts where location = 'Grover's Mill'
^
select * from my_contacts where location = 'Grover''s Mill'
('steve@onionflavoredrings.com', datetime.date(1970, 4, 1), 'スティーブ', 'ファンヨン', '国家の破壊', '同国人、ギタープレイヤー', '独身', 'パンクミュージシャン', "Grover's Mill", 'M')
$
PostgreSQLはMySQLと違って、文字列中のシングルクォートのエスケープはシングルクォートのみで、バックスラッシュ(¥)ではエスケープできないみたい。
0 コメント:
コメントを投稿