#!/usr/bin/python3 import pymysql import log import main class user_mysql(object): def __init__(self, host, username, password, database, master=None): self.host = host self.username = username self.password = password self.database = database self.db = None self.busy = False self.log_file = log.log_file self.log_print = log.log_file def connect(self): # 打开数据库连接 try: self.db = pymysql.connect(host=self.host, user=self.username, password=self.password, database=self.database) return True except Exception as e: self.log_file.logger.error('mysql连接异常: {0}'.format(e), exc_info=True, stack_info=True) return False def close(self): # 关闭数据库连接 try: self.db.close() return True except Exception as e: self.log_file.logger.error('mysql关闭异常: {0}'.format(e), exc_info=True, stack_info=True) return False def sql_action(self, sql): # 使用cursor()方法获取操作游标 cursor = self.db.cursor() try: # 执行sql语句 cursor.execute(sql) # 执行sql语句 self.db.commit() return True except Exception as e: self.log_file.logger.error('mysql执行异常: {0}'.format(e), exc_info=True, stack_info=True) # 发生错误时回滚 self.db.rollback() return False def sql_inquire(self, sql): # 使用cursor()方法获取操作游标 cursor = self.db.cursor() try: # 使用 execute() 方法执行 SQL 查询 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() return results except Exception as e: self.log_file.logger.error('mysql查询异常: {0}'.format(e), exc_info=True, stack_info=True) # 发生错误时回滚 return None def sql_inquire_all(self, sqlstr): self.busy = True self.connect() result = self.sql_inquire(sqlstr) self.close() self.busy = False return result def sql_action_all(self, sqlstr): self.busy = True self.connect() result = self.sql_action(sqlstr) self.close() self.busy = False return result sqlclient = user_mysql("localhost", "root", "1234qwer!@#$QWER", "G01_0345")