# 先要导入pymysql import logging import pymysql # 把连接参数定义成字典 import constant class Mysqldb: # 初始化方法 def __init__(self, config=constant.MYSQL_CONFIG): self.config = config # 初始化方法中调用连接数据库的方法 self.conn = self.get_conn() # 调用获取游标的方法 self.cursor = self.get_cursor() def close(self): self.conn.close() # 连接数据库的方法 def get_conn(self): # **config代表不定长参数 conn = pymysql.connect(**self.config) return conn # 获取游标 def get_cursor(self): cursor = self.conn.cursor() return cursor # 查询sql语句返回的所有数据 def select_all(self, sql): self.cursor.execute(sql) return self.cursor.fetchall() # 查询sql语句返回的一条数据 def select_one(self, sql): self.cursor.execute(sql) return self.cursor.fetchone() # 查询sql语句返回的几条数据 def select_many(self, sql, num): self.cursor.execute(sql) return self.cursor.fetchmany(num) # 增删改除了SQL语句不一样其他都是一样的,都需要提交 def execute(self, sql, args=None): try: # 执行语句 self.cursor.execute(sql, args) # 提交 self.conn.commit() except Exception as e: print("提交出错\n:", e) # logging.exception(e) # 如果出错要回滚 self.conn.rollback() def execute_many(self, sql, args=None): try: # 执行语句 self.cursor.executemany(sql, args) # 提交 self.conn.commit() except Exception as e: logging.exception(e) print("提交出错\n:", e) # 如果出错要回滚 self.conn.rollback() # 当对象被销毁时,游标要关闭,连接也要关闭 # 创建时是先创建连接后创建游标,关闭时是先关闭游标后关闭连接 def __del__(self): self.cursor.close() self.conn.close() if __name__ == '__main__': mysqldb = Mysqldb() # 插入单条数据 mysqldb.execute("insert into clients(account,pwd,rule) values(%s,%s,%s)", ("test", 123456, "\"123")) # 插入多条数据 mysqldb.execute_many("insert into clients(account,pwd,rule) values(%s,%s,%s)", [("test", 123456, "\"123"), ("test", 123456, "\"123")])