開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 9.(The Context Management Protocol: Hooking Into Python's With Statement) の SHARPEN YOUR PENCIL(No. 6559) を取り組んでみる。
Relational Database は MySQL、MariaDBの代わりに SQLite を使用。
SHARPEN YOUR PENCIL(No. 6559)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
class UseDatabase:
def __init__(self, dbconfig: dict) -> None:
self.dbconfig = dbconfig
def __enter__(self) -> 'cursor':
self.conn = sqlite3.connect(self.dbconfig['database'] + '.sql')
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_value, exc_trace) -> None:
self.conn.commit()
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
dbconfig = {'host': '127.0.0.1',
'user': 'vsearch',
'password': 'vsearchpasswd',
'database': 'vsearchlogDB'}
with UseDatabase(dbconfig) as cursor:
_SQL = '''select * from log'''
cursor.execute(_SQL)
for row in cursor.fetchall():
print(row)
入出力結果(Terminal, IPython)
$ ./DBcm.py
(None, '2017-03-30 10:30:01', 'Head First Python', 'aeiou', '127.0.0.1', 'safari', "{'o', 'e', 'a', 'i'}")
(None, '2017-03-30 10:30:24', 'SQLite', 'aeiou', '127.0.0.1', 'safari', "{'e', 'i'}")
$
0 コメント:
コメントを投稿