python pyqt5 mysql QMessageBox用import mysql.connectorpython mysql 实现注册登录
时间: 2023-11-05 18:14:45 浏览: 144
以下是一个简单的示例代码,使用 PyQT5 和 MySQL 实现注册和登录功能:
```python
import mysql.connector
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QMessageBox
# 连接 MySQL 数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 注册函数
def register(username, password):
mycursor = mydb.cursor()
sql = "INSERT INTO users (username, password) VALUES (%s, %s)"
val = (username, password)
mycursor.execute(sql, val)
mydb.commit()
QMessageBox.information(None, "Registration Successful", "You have successfully registered!")
# 登录函数
def login(username, password):
mycursor = mydb.cursor()
sql = "SELECT * FROM users WHERE username = %s AND password = %s"
val = (username, password)
mycursor.execute(sql, val)
result = mycursor.fetchone()
if result:
QMessageBox.information(None, "Login Successful", "You have successfully logged in!")
else:
QMessageBox.warning(None, "Login Failed", "Invalid username or password.")
# 创建 GUI
app = QtWidgets.QApplication([])
dlg = uic.loadUi("login.ui")
# 注册按钮点击事件
def register_clicked():
username = dlg.register_username.text()
password = dlg.register_password.text()
register(username, password)
# 登录按钮点击事件
def login_clicked():
username = dlg.login_username.text()
password = dlg.login_password.text()
login(username, password)
dlg.register_button.clicked.connect(register_clicked)
dlg.login_button.clicked.connect(login_clicked)
dlg.show()
app.exec()
```
需要注意的是,上述代码中的 `mydatabase` 应该替换为你自己的数据库名称,而 `yourusername` 和 `yourpassword` 则应该替换为你的 MySQL 用户名和密码。此外,还需要在 MySQL 中创建一个名为 `users` 的表,包含 `username` 和 `password` 两个字段。
阅读全文