python_数据库连接封装类
如下为数据库连接封装为类,通过析构和构造函数进行自连接和自关闭
class MySQL: def __init__(self): self.conn = pymysql.connect(host='IP', user='jxz', password='123456', db='jxz', port=3306, charset='utf8', autocommit=True) self.cur = self.conn.cursor(pymysql.cursors.DictCursor) def __del__(self): self.cur.close() self.conn.close() print('连接已经被关闭了') def execute_one(self,sql): self.cur.execute(sql) return self.cur.fetchone() def execute_many(self,sql): self.cur.execute(sql) return self.cur.fetchall() m = MySQL() m.execute_one('show tables;')