MySQL数据库连接
import pymysql import contextlib @contextlib.contextmanager def get_cursor(): """获取数据库光标""" db_settings = { 'host': '', 'user': '', 'password': '', 'database': '', 'charset': 'utf8', 'cursorclass': pymysql.cursors.DictCursor } try: conn = pymysql.connect(**db_settings) # 使用yield不但能够返回cursor # 而且cursor使用完毕后还会回到下一行继续执行 # 这样数据库就能关闭! yield conn.cursor() conn.commit() except: conn.rollback() raise finally: conn.close()
with db.get_cursor() as cursor: sql = '' cursor.execute(sql) rows = cursor.fetchall() ss = [] for r in rows: s = Subject() for key in r: setattr(s, key, r[key]) ss.append(s) return ss