python pyqt5 mysql用import mysql.connector实现注册并判断两次密码是否一致,并运行
时间: 2024-05-01 22:20:16 浏览: 128
首先,需要安装 mysql-connector-python 库,可以使用以下命令进行安装:
```
pip install mysql-connector-python
```
接下来,可以使用以下代码实现注册并判断两次密码是否一致:
```python
from PyQt5.QtWidgets import *
import mysql.connector
class RegisterWindow(QWidget):
def __init__(self):
super().__init__()
self.username_label = QLabel('Username:', self)
self.username_edit = QLineEdit(self)
self.password_label = QLabel('Password:', self)
self.password_edit = QLineEdit(self)
self.password_edit.setEchoMode(QLineEdit.Password)
self.confirm_password_label = QLabel('Confirm Password:', self)
self.confirm_password_edit = QLineEdit(self)
self.confirm_password_edit.setEchoMode(QLineEdit.Password)
self.register_button = QPushButton('Register', self)
self.init_ui()
def init_ui(self):
self.setGeometry(100, 100, 300, 200)
self.setWindowTitle('Register')
grid = QGridLayout()
grid.addWidget(self.username_label, 0, 0)
grid.addWidget(self.username_edit, 0, 1)
grid.addWidget(self.password_label, 1, 0)
grid.addWidget(self.password_edit, 1, 1)
grid.addWidget(self.confirm_password_label, 2, 0)
grid.addWidget(self.confirm_password_edit, 2, 1)
grid.addWidget(self.register_button, 3, 1)
self.setLayout(grid)
self.register_button.clicked.connect(self.register)
def register(self):
username = self.username_edit.text()
password = self.password_edit.text()
confirm_password = self.confirm_password_edit.text()
if password != confirm_password:
QMessageBox.warning(self, 'Warning', 'Passwords do not match.')
return
try:
conn = mysql.connector.connect(
user='username',
password='password',
host='localhost',
database='database_name'
)
cursor = conn.cursor()
# Check if username already exists
query = f"SELECT * FROM users WHERE username = '{username}'"
cursor.execute(query)
if cursor.fetchone():
QMessageBox.warning(self, 'Warning', 'Username already exists.')
return
# Insert user into database
query = f"INSERT INTO users (username, password) VALUES ('{username}', '{password}')"
cursor.execute(query)
conn.commit()
QMessageBox.information(self, 'Success', 'Registration successful.')
except mysql.connector.Error as error:
QMessageBox.warning(self, 'Error', f"Error connecting to MySQL: {error}")
finally:
if conn.is_connected():
cursor.close()
conn.close()
if __name__ == '__main__':
app = QApplication([])
register_window = RegisterWindow()
register_window.show()
app.exec_()
```
在这个例子中,我们创建了一个注册窗口,包含用户名、密码、确认密码和注册按钮。我们使用 MySQL 数据库来存储用户数据。当用户点击注册按钮时,我们将获取输入的用户名和密码,并检查两次密码是否一致。如果不一致,我们将显示警告消息框。接下来,我们将连接到数据库,并检查用户名是否已存在。如果用户名已存在,我们将显示警告消息框。否则,我们将插入新用户数据到数据库中,并显示成功消息框。最后,我们关闭数据库连接。
阅读全文