pymysql连接工具类
import pymysql'''
数据库连接工具类
'''class MySQLConnection:def __init__(self, host, port, user, password, database):self.host = hostself.port = portself.user = userself.password = passwordself.database = databaseself.conn = Noneself.cursor = None# 连接数据库def connect(self):self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,database=self.database,charset='utf8mb4')self.cursor = self.conn.cursor()# 断开连接def disconnect(self):if self.conn:self.conn.close()# 查询def execute_query(self, sql):self.cursor.execute(sql)result = self.cursor.fetchall()return result#更新def execute_update(self, sql):self.cursor.execute(sql)self.conn.commit()return self.cursor.rowcount# 关闭驱动def close_cursor(self):if self.cursor:self.cursor.close()
查询数据类
'''
class CoverageProject(object):def __init__(self):passdef test(self):# mysql 连接对象connection = MySQLConnection('1.1.1.0', 3306, 'username', 'password', 'test')connection.connect()result = connection.execute_query('sql')# 直接打印查询出的数据for row in result:print(row)print('===========================================================')# 将查询出数据的key与value进行对应,再打印row_headers = [x[0] for x in connection.cursor.description] # this will extract row headersfor row in result:print(dict(zip(row_headers, row)))if __name__ == '__main__':c = CoverageProject()c.test()
执行结果