使用Python的read_sql_query函数
import os
import tkinter as tk
import pandas as pd
import pymysql
import pyperclip
# 连接到数据库
conn = pymysql.connect(
host='',
port=,
user='',
password='',
database=''
)
def format_sql():
sql = text_input.get("1.0", "end-1c") # 获取输入的SQL语句
if sql.strip() == "":
sql = "SELECT * FROM a l join b ty on l.device_type = ty.device_type limit 3"
# 执行SQL语句并将结果存储到DataFrame中
df = pd.read_sql_query(sql, conn)
# 将DataFrame保存到Excel文件
df.to_excel('query_results.xlsx', index=False)
ui = df.to_html()
pyperclip.copy(ui)
print(ui)
try:
# 调用操作系统命令来导出文件并自动打开
os.system(f'start {"query_results.xlsx"}')
except Exception as e:
print("发生错误:", str(e))
text_output.delete("1.0", "end") # 清空输出框
text_output.insert("1.0", "生成完成\n"+ui) # 将规整后的SQL显示在输出框中
# 创建窗口
window = tk.Tk()
window.title("自定义SQL导出工具----By Jonie")
# 创建输入框
text_input = tk.Text(window, height=2, width=50)
text_input.pack(side='top',fill='both',expand=True)
# 创建按钮
button = tk.Button(window, text="文件生成", command=format_sql)
button.pack(side='top',fill='both',expand=True)
# 创建输出框
text_output = tk.Text(window, height=5, width=50)
text_output.pack(side='top',fill='both',expand=True)
# 运行窗口
window.mainloop()
# 关闭连接
conn.close()
