pymysql操作
import pymysql
# 连接数据库
conn = pymysql.connect(host=None,user=None,password=None,database=None,charset="utf8")
#实例化一个操作光标
cursor1 = conn.cursor() #执行完以元组的形式返回
cursor2 = conn.cursor(cursor=pymysql.cursors.DictCursor) # 执行完以列表包字典的形式返回数据
# 定义要执行的sql语句
sql = """
select * from hotel_base limit 0,1000
"""
# 执行sql语句,返回数据
cursor1.execute(sql)
cursor1.fetchall() # 返回全部数据
cursor1.fetchone() # 返回单条数据
# 关闭数据库连接
conn.close()
pymysql封装
import pymysql
class MysqlHandler():
def __init__(self,host=None,user=None,password=None,database=None,port=None):
# 连接数据库
self.conn = pymysql.connect(host=host,user=user,
password=password,database=database,
port=port,charset="utf8")
# 游标,输出格式为字典
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
def select(self,sql,one=True):
'''数据库查询'''
self.cursor.execute(sql)
if one:
return self.cursor.fetchone()
else:
return self.cursor.fetchall()
def close(self):
'''关闭数据库连接'''
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
from common import yaml_handler
from config.config import DataBasePath
# 实例化一个yaml文件操作手柄连接数据库配置文件
yaml_handler = yaml_handler.YamlHandler(DataBasePath.database_path)
# 读取数据库地址信息
data = yaml_handler.yaml_read()["test_pms_database"]
# 实例化一个mysql_handler,连接数据库
mysql_handler = MysqlHandler(host=data["host"],port=data["port"],user=data["username"],password=data["password"],database=data["database"])
# 编写需要执行的SQL语句
sql = "select * from bus_hotel_base limit 0,1000"
# 执行查询SQL语句,获取查询结果
select_data = mysql_handler.select(sql,one=False)
# 打印查询结果
print(select_data)