pymysql连接工具类
import pymysql
'''
数据库连接工具类
'''
class MySQLConnection:
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.conn = None
self.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):
pass
def 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 headers
for row in result:
print(dict(zip(row_headers, row)))
if __name__ == '__main__':
c = CoverageProject()
c.test()
执行结果