免费分享刚刚写的一个小程序,测试通过没问题,解BUG也就花了半小时吧
有更好的方法欢迎评论区推给我谢谢。
import tkinter as tk from tkinter import messagebox import pymysql def get_db_info(db_source): if db_source=='database1': hostname = e1.get() username = e2.get() password = e3.get() database = e4.get() port = e5.get() elif db_source=='database2': hostname = e11.get() username = e22.get() password = e33.get() database = e44.get() port = e55.get() return hostname, username, password, database, port def test_connection(db_source): try: hostname, username, password, database, port = get_db_info(db_source) connection = pymysql.connect(host=hostname, user=username, password=password, db=database, port=int(port)) with connection.cursor() as cursor: cursor.execute("SELECT VERSION()") result = cursor.fetchone() messagebox.showinfo("数据库版本", f"数据库版本: {result}") connection.close() except pymysql.MySQLError as e: messagebox.showerror("连接错误", f"无法连接到数据库: {e}") root = tk.Tk() root.title("数据库连接测试") tk.Label(root, text="源端数据库信息").grid(row=0, column=0) tk.Label(root, text="主机名: ").grid(row=1, column=0) tk.Label(root, text="用户名: ").grid(row=2, column=0) tk.Label(root, text="密码: ").grid(row=3, column=0) tk.Label(root, text="数据库名: ").grid(row=4, column=0) tk.Label(root, text="端口: ").grid(row=5, column=0) e1 = tk.Entry(root) e2 = tk.Entry(root) e3 = tk.Entry(root, show='*') e4 = tk.Entry(root) e5 = tk.Entry(root) e1.grid(row=1, column=1) e2.grid(row=2, column=1) e3.grid(row=3, column=1) e4.grid(row=4, column=1) e5.grid(row=5, column=1) button = tk.Button(root, text="测试连接", command=test_connection('database1')) button.grid(row=6, column=0, sticky=tk.W, pady=10) tk.Label(root, text="目标端数据库信息").grid(row=7, column=0) tk.Label(root, text="主机名: ").grid(row=8, column=0) tk.Label(root, text="用户名: ").grid(row=9, column=0) tk.Label(root, text="密码: ").grid(row=10, column=0) tk.Label(root, text="数据库名: ").grid(row=11, column=0) tk.Label(root, text="端口: ").grid(row=12, column=0) e11 = tk.Entry(root) e22 = tk.Entry(root) e33 = tk.Entry(root, show='*') e44 = tk.Entry(root) e55 = tk.Entry(root) e11.grid(row=8, column=1) e22.grid(row=9, column=1) e33.grid(row=10, column=1) e44.grid(row=11, column=1) e55.grid(row=12, column=1) button = tk.Button(root, text="测试连接", command=test_connection('database2')) button.grid(row=13, column=0, sticky=tk.W, pady=10) root.mainloop()
运行结果如下:
关注公众号,多多交流!
标签:连通性,python,text,column,测试通过,grid,tk,root,row From: https://blog.csdn.net/m0_38111284/article/details/141054947