【Python】mysql-connector-pythonでwith構文を使えるようにする
Pythonでデータベースの操作するときはmysql-connector-pythonを使っているのですが、with構文を使えず毎回closeを書くのが面倒なのでwith構文に対応したラッパークラスを作りました。
with構文に対応したmysql-connector-pythonのラッパークラス
ソースコードは以下のとおりです。
使い方
使い方は以下のとおりです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from db import Connector account = { "db": "databasename", "host": "ip address", "user": "username", "passwd": "password" } with Connector(account) as connect: cursor = connect.cursor() cursor.execut("SELECT * FROM tbl") results = cursor.fetchall() cursor.close() |
コメントを投稿するにはログインが必要です。