Graphical User Interface(GUI)是一种用户与计算机程序互动的方式,它通常通过屏幕上的可视化元素(如按钮,文本框和菜单)来呈现和控制程序的操作。其中很多程序需要与数据库进行交互以存储和检索数据,而MySQL是一种流行的开源数据库管理系统。
import mysql.connectorfrom tkinter import *# 创建GUI窗口root = Tk()root.title("MySQL数据管理系统")root.geometry("400x300")# 连接MySQL数据库mydb = mysql.connector.connect(host="localhost",user="root",password="password",database="mydatabase")# 创建光标mycursor = mydb.cursor()# 创建出入数据的函数def insert_data():username = username_entry.get()password = password_entry.get()sql = "INSERT INTO users (username, password) VALUES (%s, %s)"val = (username, password)mycursor.execute(sql, val)mydb.commit()# 创建用户界面username_label = Label(root, text="用户名")username_label.pack()username_entry = Entry(root)username_entry.pack()password_label = Label(root, text="密码")password_label.pack()password_entry = Entry(root, show="*")password_entry.pack()insert_button = Button(root, text="插入数据", command=insert_data)insert_button.pack()root.mainloop()
在上面的代码中,我们首先使用了Python的mysql.connector模块连接到MySQL数据库。我们还创建了一个窗口,其中包含用于输入数据的文本框和一个用于将数据插入到数据库的按钮。当用户点击"插入数据"按钮时,insert_data函数将被调用,该函数获取文本框中的值并使用SQL语句将其插入到数据库中。