你可以使用pandas库来连接 MySQL 数据库,并将查询结果导出到 Excel 文件。以下是一个简单的示例:
安装 pandas 和 openpyxl:
如果还没有安装,首先需要安装 pandas 和 openpyxl:
pip install pandas openpyxl
连接 MySQL 数据库并导出到 Excel:
使用以下脚本连接 MySQL 数据库,执行查询,将结果导入 pandas 的 DataFrame 中,最后将 DataFrame 保存为 Excel 文件。
import pandas as pd
import mysql.connector
# 替换以下信息为你的实际数据库信息
host = "localhost"
user = "your_username"
password = "your_password"
database = "your_database"
# 建立数据库连接
connection = mysql.connector.connect(
host=host,
user=user,
password=password,
database=database
)
# 执行 SQL 查询
query = "SELECT * FROM your_table"
df = pd.read_sql(query, connection)
# 保存 DataFrame 到 Excel 文件
df.to_excel("output.xlsx", index=False)
# 关闭数据库连接
connection.close()
确保替换代码中的 your_username、your_password、your_database、your_table 等信息为你实际的数据库信息。这个脚本将查询结果保存到名为 output.xlsx 的 Excel 文件中。你可以根据需要修改查询语句和保存的文件名。
