mysql實現with上下文管理器----python
阿新 • • 發佈:2018-12-22
from pymysql import connect class DBOpen(object): # 初始化 def __init__(self, databasename): # 建立Connection連線 self.conn = connect(host='localhost', port=3306, database=databasename, user='root', password='mysql', charset='utf8') # 獲得Cursor物件 self.cs1 = self.conn.cursor() # 返回操作符 def __enter__(self): return self.cs1 # 退出 def __exit__(self, exc_type, exc_val, exc_tb): # 關閉之前做一個統一的提交 self.conn.commit() # 1.3 關閉 self.cs1.close() self.conn.close() with DBOpen("stock_db") as cs: cs.execute("select * from info;") data = cs.fetchall() for temp in data: print(temp)