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.
|
|
|
|
import pymysql
|
|
|
|
|
from tkinter import Tk, messagebox
|
|
|
|
|
|
|
|
|
|
def start_mysql_process():
|
|
|
|
|
config = {
|
|
|
|
|
'host': 'localhost',
|
|
|
|
|
'port': 3306,
|
|
|
|
|
'user': 'root',
|
|
|
|
|
'password': '123321',
|
|
|
|
|
'db': 'gushici',
|
|
|
|
|
'charset': 'utf8mb4',
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
# 创建连接
|
|
|
|
|
connection = pymysql.connect(**config)
|
|
|
|
|
print("数据库连接成功")
|
|
|
|
|
|
|
|
|
|
# 显示连接成功的消息框
|
|
|
|
|
show_success_popup()
|
|
|
|
|
|
|
|
|
|
# 创建游标,用于执行SQL命令
|
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
|
# 执行一个查询示例
|
|
|
|
|
cursor.execute("SELECT * FROM shici LIMIT 5")
|
|
|
|
|
|
|
|
|
|
# 获取查询结果
|
|
|
|
|
result = cursor.fetchall()
|
|
|
|
|
for row in result:
|
|
|
|
|
print(row)
|
|
|
|
|
|
|
|
|
|
# 对于只读操作,commit不是必需的,但保持原样以确保其他类型操作的完整性
|
|
|
|
|
connection.commit()
|
|
|
|
|
|
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
|
print(f"数据库查询过程中发生错误: {e}")
|
|
|
|
|
finally:
|
|
|
|
|
# 连接关闭已经在with语句中自动完成,这里不需要额外处理
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def show_success_popup():
|
|
|
|
|
"""显示数据库连接成功的消息框"""
|
|
|
|
|
root = Tk()
|
|
|
|
|
root.withdraw() # 隐藏主窗口,只显示消息框
|
|
|
|
|
messagebox.showinfo("连接状态", "数据库连接成功!")
|
|
|
|
|
root.destroy() # 销毁窗口对象,结束进程
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
start_mysql_process()
|