import pymysql class Db: def __init__(self,host,user,password,db,port=3306,charset=‘utf8‘): #构造函数,实例化的时候自动执行构造函数 self.db_info = {‘user‘: user, ‘password‘: password, ‘host‘: host, ‘db‘: db, ‘port‘: port,‘charset‘:charset,‘autocommit‘: True} self.__connect() #__代表私有方法 def __del__(self): #析构函数 self.__close() print("关闭数据库") def __connect(self): #__代表私有方法 # db_info = {‘user‘: ‘xmb‘, ‘password‘: ‘123456‘, ‘host‘: ‘127.0.0.0‘, ‘db‘: ‘xmb‘, ‘port‘: 3306, # ‘charset‘: ‘utf8‘, ‘autocommit‘: True} try: self.conn = pymysql.connect(**self.db_info) # 建立连接 except Exception as e: print("数据库连接不上") raise Exception("数据库连接不上,请检查数据库连接信息") else: self.cur = self.conn.cursor(pymysql.cursors.DictCursor) # 游标 def execute_many(self,sql): self.cur.execute(sql) return self.cur.fetchall() def excute_one(self,sql): self.cur.execute(sql) return self.cur.fetchone() def __close(self): #__代表私有方法 self.conn.close() self.cur.close() def export_excel(self,table_name): pass mysql = Db(‘127.0.0.0‘,‘xmb‘,‘123456‘,‘xmb‘) result = mysql.excute_one(‘select * from app_myuser ‘) print(result)
原文:https://www.cnblogs.com/xumb/p/11963570.html