開発環境
- macOS Mojave - Apple
- Emacs (Text Editor)
- Python 3.7 (プログラミング言語)
Head First Python 第2版 ―頭とからだで覚えるPythonの基本 (Paul Barry (著)、嶋田 健志 (監修)、木下 哲也 (翻訳)、オライリージャパン)の9章(コンテキストマネジメントプロトコル - with 文を使う)、自分で考えてみよう(p. 345)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3
import mysql.connector
dbconfig = {'host': '127.0.0.1',
'user': 'vsearch',
'password': 'vsearchpasswd',
'database': 'vsearchlogDB', }
class UseDataBase:
def __init__(self, config: dict) -> None:
self.configuration = config
def __enter__(self) ->'cursor':
print('enter')
self.conn = mysql.connector.connect(**dbconfig)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_value, exc_trace) -> None:
print('exit')
self.conn.commit()
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
with UseDataBase(dbconfig) as db:
print(db)
入出力結果(Terminal, Jupyter(IPython))
$ ./sample3.py enter MySQLCursor: (Nothing executed yet) exit $
0 コメント:
コメントを投稿