class OperMysql: def __init__(self, host, port, username, passwd, database='study'): self.host = host self.port = port self.username = username self.passwd = passwd self.database = database def db_connect(self): try: conn = pymysql.connect(host=self.host, port=self.port, user=self.username, password=self.passwd, database=self.database) cur = conn.cursor() return conn, cur except Exception as error: logging.error('connect faild!') raise error @staticmethod def exec_sql(cursor, strsql): try: cursor.execute(strsql) except Exception as error: logging.error("insert error %s" % error) with open(cfg["error_file"], 'a+', encoding="utf-8") as f: f.write(strsql + '\n')1. 实例话类,然后调用connect函数创建连接和游标2. 执行sql失败,写日志和吧错误sql写入文件。3. 注意数据库事务需要自己控制,conn.commit;