You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.9 KiB
63 lines
1.9 KiB
import pymysql
|
|
import tkinter as tk
|
|
from tkinter import scrolledtext
|
|
|
|
def connect_to_db(config):
|
|
"""连接到数据库"""
|
|
try:
|
|
connection = pymysql.connect(**config)
|
|
print("Connected to the MySQL database successfully!")
|
|
return connection
|
|
except pymysql.Error as e:
|
|
print(f"Error connecting to MySQL: {e}")
|
|
return None
|
|
|
|
def query_data(connection, query):
|
|
"""执行SQL查询并返回数据"""
|
|
if connection is None:
|
|
return None
|
|
|
|
try:
|
|
with connection.cursor() as cursor:
|
|
cursor.execute(query)
|
|
result = cursor.fetchall()
|
|
return result
|
|
except pymysql.Error as e:
|
|
print(f"Error executing query: {e}")
|
|
return None
|
|
|
|
def display_data_in_gui(data):
|
|
"""在Tkinter窗口中显示数据"""
|
|
window = tk.Tk()
|
|
window.title("Poems Data Display")
|
|
|
|
text_area = scrolledtext.ScrolledText(window, wrap=tk.WORD)
|
|
text_area.pack(fill=tk.BOTH, expand=True)
|
|
|
|
# 假设查询结果的列是固定的,这里直接按位置索引处理元组
|
|
column_names = ["id", "title", "dynasty", "author", "content"] # 请根据实际表结构调整列名列表
|
|
|
|
for row in data:
|
|
# 如果你知道具体的列顺序,可以直接按索引提取
|
|
formatted_row = '\n'.join(f'{name}: {value}' for name, value in zip(column_names, row))
|
|
text_area.insert(tk.END, formatted_row + "\n-----------------\n")
|
|
|
|
window.mainloop()
|
|
|
|
if __name__ == "__main__":
|
|
db_config = {
|
|
'host': 'localhost',
|
|
'port': 3306,
|
|
'user': 'root',
|
|
'password': '123321',
|
|
'db': 'gushici',
|
|
'charset': 'utf8mb4'
|
|
}
|
|
|
|
connection = connect_to_db(db_config)
|
|
if connection:
|
|
query = "SELECT * FROM poems" # 查询poems表的所有内容
|
|
data = query_data(connection, query)
|
|
if data:
|
|
display_data_in_gui(data)
|
|
connection.close() |