Код, размещенный ниже, на самом деле является разновидностью POC (Proof of Concept) и может быть свободно изменен любым удобным для вас способом. Он тестирует стандартную настройку подключения Python 3.10 к MySQL 8.0.29 работающему на Ubuntu 20.04.4
Code
(.env) boris@boris-All-Series:~/MYSQL8029$ cat PyQT5MySQL8.py
#!/usr/bin/python3
import sys
import mysql.connector
from PyQt5.QtWidgets import QTableWidget, QApplication, QMainWindow, QTableWidget
from PyQt5.QtWidgets import QTableWidgetItem, QWidget, QPushButton, QLineEdit
from PyQt5 import QtGui
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.con()
self.setGeometry(100, 100, 500, 600)
self.setWindowTitle('Scores List')
self.tb = Tb(self)
self.btn = QPushButton('Refresh View', self)
self.btn.resize(150, 40)
self.btn.move(300, 10)
self.btn.clicked.connect(self.upd)
self.idp = QLineEdit(self)
self.idp.resize(150, 40)
self.idp.move(300, 60)
self.idp.setReadOnly(True)
self.fio = QLineEdit(self)
self.fio.resize(150, 40)
self.fio.move(300, 110)
self.oce = QLineEdit(self)
self.oce.resize(150, 40)
self.oce.move(300, 160)
self.btn = QPushButton('Add row', self)
self.btn.resize(150, 40)
self.btn.move(300, 210)
self.btn.clicked.connect(self.ins)
self.btn = QPushButton('Update row', self)
self.btn.resize(150, 40)
self.btn.move(300, 260)
self.btn.clicked.connect(self.change)
self.btn = QPushButton('Delete row', self)
self.btn.resize(150, 40)
self.btn.move(300, 310)
self.btn.clicked.connect(self.dels)
# local connect to mysql datatabase
def con(self):
self.conn = mysql.connector.connect(user = "root",
password = "***********",
host = "127.0.0.1",
port = 3306,
database = "db1")
self.cur = self.conn.cursor()
def upd(self): # insert record into table
self.conn.commit()
self.tb.updt()
self.idp.setText('')
self.fio.setText('')
self.oce.setText('')
def ins(self):
fio, oce = self.fio.text(), self.oce.text()
try:
self.cur.execute("insert into students (name, ocenka) values (%s,%s)",(fio,oce))
except:
pass
self.upd()
def change(self): # update record in table
fio, oce = self.fio.text(), self.oce.text()
try:
ids = int(self.idp.text())
except:
return
self.cur.execute("update students set name=%s,ocenka=%s where id=%s",(fio,oce,ids,))
self.upd()
# delete record from table
def dels(self):
try:
ids = int(self.idp.text()) # row identifier
except:
return
self.cur.execute("delete from students where id=%s",(ids,))
self.upd()
class Tb(QTableWidget):
def __init__(self, wg):
self.wg = wg # remember window to show table
super().__init__(wg)
self.setGeometry(10, 10, 280, 500)
self.setColumnCount(3)
self.verticalHeader().hide();
self.updt() # обновить таблицу
self.setEditTriggers(QTableWidget.NoEditTriggers)
self.cellClicked.connect(self.cellClick) # catch mouse click on table
def updt(self):
self.clear()
self.setRowCount(0);
self.setHorizontalHeaderLabels(['id', 'Name', 'Score'])
self.wg.cur.execute("select * from students order by id")
rows = self.wg.cur.fetchall()
i = 0
for elem in rows:
self.setRowCount(self.rowCount() + 1)
j = 0
for t in elem: # fill in the line
self.setItem(i, j, QTableWidgetItem(str(t).strip()))
j += 1
i += 1
self.resizeColumnsToContents()
# Reaction on mouse click inside table
def cellClick(self, row, col): # row - row number, col - column number
self.wg.idp.setText(self.item(row, 0).text())
self.wg.fio.setText(self.item(row, 1).text().strip())
self.wg.oce.setText(self.item(row, 2).text().strip())
app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())
No comments:
Post a Comment