pyqt5给mysql插入数据
时间: 2023-07-26 08:33:57 浏览: 98
以下是使用PyQt5将数据插入MySQL数据库的示例代码:
```python
import mysql.connector
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.lbl1 = QLabel('Name', self)
self.lbl1.move(50, 30)
self.lbl2 = QLabel('Age', self)
self.lbl2.move(50, 70)
self.lbl3 = QLabel('Country', self)
self.lbl3.move(50, 110)
self.name = QLineEdit(self)
self.name.move(150, 30)
self.age = QLineEdit(self)
self.age.move(150, 70)
self.country = QLineEdit(self)
self.country.move(150, 110)
self.btn = QPushButton('Insert', self)
self.btn.move(150, 150)
self.btn.clicked.connect(self.insert_data)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Insert Data')
self.show()
def insert_data(self):
name = self.name.text()
age = self.age.text()
country = self.country.text()
# 创建MySQL数据库连接
cnx = mysql.connector.connect(user='username', password='password',
host='localhost',
database='mydatabase')
cursor = cnx.cursor()
# 插入数据
add_data = ("INSERT INTO mytable "
"(name, age, country) "
"VALUES (%s, %s, %s)")
data = (name, age, country)
cursor.execute(add_data, data)
# 提交更改并关闭连接
cnx.commit()
cursor.close()
cnx.close()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
在这个示例中,我们创建了一个简单的GUI应用程序,用户可以输入姓名,年龄和国家,并将这些信息插入到MySQL数据库中。在 `insert_data()` 方法中,我们创建了一个MySQL连接,然后使用 `cursor.execute()` 方法将数据插入到表中。
注意,我们需要替换示例中的 `username`,`password`,`localhost`,`mydatabase`,`mytable` 为实际的MySQL连接信息和表名。
阅读全文
相关推荐


















