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

6 months ago
import pymysql
6 months ago
import tkinter as tk
from tkinter import scrolledtext
6 months ago
6 months ago
def connect_to_db(config):
"""连接到数据库"""
6 months ago
try:
connection = pymysql.connect(**config)
6 months ago
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:
6 months ago
with connection.cursor() as cursor:
6 months ago
cursor.execute(query)
6 months ago
result = cursor.fetchall()
6 months ago
return result
except pymysql.Error as e:
print(f"Error executing query: {e}")
return None
6 months ago
6 months ago
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()
6 months ago
6 months ago
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()