import mysql.connector
import pandas as pd
# 连接到MySQL数据库
config = {
'user': 'root', # 替换为你的数据库用户名
'password': '66666', # 替换为你的数据库密码
'host': 'localhost', # 替换为你的数据库主机
'database': 'mydatabase', # 替换为你的数据库名称
}
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
# 查询SQL语句
query = """
SELECT *
FROM `2021_chengban`
WHERE 汇总 LIKE '%投诉%' AND 汇总 LIKE '%噪音%';
"""
# 执行查询
cursor.execute(query)
# 将查询结果转换为Pandas DataFrame
df = pd.DataFrame(cursor.fetchall(), columns=[desc[0] for desc in cursor.description])
# 导出到Excel文件
output_file = r'F:\output_file.xlsx' # 替换为输出文件路径
writer = pd.ExcelWriter(output_file, engine='openpyxl')
df.to_excel(writer, index=False)
writer._save()
# 关闭数据库连接
cursor.close()
cnx.close()
首先确保你的python有mysql.connector这个工具,咩有的话就pip一下