链接数据库方法
连接数据库
class DatabaseConnection:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = None
self.cursor = None
def connect(self):
"""建立数据库连接"""
self.connection = pymysql.connect(host=self.host, user=self.user,
password=self.password, db=self.database, charset='utf8')
self.cursor = self.connection.cursor()
def execute_query(self, sql):
"""执行查询操作"""
if self.connection is None:
self.connect()
self.cursor.execute(sql)
results=self.cursor.fetchall()
columns = [column[0] for column in self.cursor.description] #设置返回值回显列名字典类型
rows_as_dict = []
for row in results:
row_dict = dict(zip(columns, row))
rows_as_dict.append(row_dict)
return rows_as_dict
def execute_transaction(self, sql):
"""执行事务操作"""
if self.connection is None:
self.connect()
self.cursor.execute(sql)
self.connection.commit()
def close_connection(self):
"""关闭数据库连接"""
if self.connection is not None:
self.connection.close()
#该方法为pandas设置表宽优化显示
def set_option():
pd.set_option('display.max_colwidth', 50)
pd.set_option('display.max_rows', None) # 设置显示行的最大数目为无限
pd.set_option('display.max_columns', None) # 设置显示列的最大数目为无限
pd.set_option('display.width', None) # 自动检测控制台的宽度
下面查询所有的数据库表就可以直接引用此对象进行查询使用
列如:
对比表头 (import pandas as pd 引用pandas后直接封装数据进行对比pd.DataFrame(db_test.execute_query(sql))
查询数据库表数据