python链接mysql ui界面
时间: 2023-10-02 15:11:27 浏览: 105
要在 Python 中连接 MySQL 并创建 UI 界面,可以使用 PyMySQL 和 PyQt5 库。以下是一个示例代码,可以实现连接 MySQL 数据库和创建简单的 UI 界面。
```python
import sys
import pymysql
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle("MySQL Connection")
# 创建表格
self.table = QTableWidget(self)
self.table.setGeometry(50, 50, 700, 500)
self.table.setColumnCount(3)
self.table.setHorizontalHeaderLabels(['ID', 'Name', 'Age'])
# 连接 MySQL 数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='mydb')
cursor = conn.cursor()
# 查询数据
cursor.execute("SELECT * FROM mytable")
data = cursor.fetchall()
# 将数据添加到表格中
self.table.setRowCount(len(data))
for i, row in enumerate(data):
for j, col in enumerate(row):
self.table.setItem(i, j, QTableWidgetItem(str(col)))
# 关闭数据库连接
conn.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在此示例中,我们创建了一个名为 `MainWindow` 的类,该类继承自 `QMainWindow` 类。我们在 `initUI` 方法中创建了一个表格,连接了 MySQL 数据库,并从数据库中检索数据。我们将数据添加到表格中,并在最后关闭了数据库连接。
要运行此示例,您需要确保已安装 PyMySQL 和 PyQt5 库,并将数据库连接信息替换为自己的信息。
阅读全文
相关推荐















