def query_employee(self, id): conn = pymysql.connect(host='39.99.214.172', user='root', password='Solotion.123', database='jj_tset') cursor = conn.cursor() cursor.execute("SELECT * FROM employee_table WHERE user_id='%s'" % id) result = cursor.fetchone() conn.close() return result # 读取数据 def read_data(self): data = self.ser.readline() if data: # 解析数据 id = data.decode().strip() # 查询员工信息 result = self.query_employee(id) if result: # 更新UI界面 self.id_label.setText("员工ID:" + result[0]) self.name_label.setText("姓名:" + str(result[1])) self.six_label.setText("性别:" + result[2]) self.sfz_label.setText("身份证:" + str(result[3])) self.tel_label.setText("电话:" + result[4]) else: # 显示空白信息 self.id_label.setText("员工ID:") self.name_label.setText("姓名:") self.six_label.setText("性别:") self.sfz_label.setText("身份证:") self.tel_label.setText("电话:") # 定时读取数据 QTimer.singleShot(100, self.read_data) def closeEvent(self, event): # 关闭串口 self.ser.close()怎么改为多线程来优化程序性能,将耗时的操作放在子线程中执行,避免阻塞主线程
时间: 2023-12-31 11:05:19 浏览: 97
conn_sql.rar_CONN_SQL.asp_asp conn sql_conn sql_conn.asp
可以使用Python中的`QThread`来实现多线程功能,将`read_data`函数中的查询数据库操作放在子线程中执行,避免阻塞主线程。示例代码如下:
```python
from PyQt5.QtCore import QThread, QTimer, pyqtSignal
class QueryThread(QThread):
query_result = pyqtSignal(object)
def __init__(self, id):
super().__init__()
self.id = id
def run(self):
conn = pymysql.connect(host='39.99.214.172', user='root', password='Solotion.123', database='jj_tset')
cursor = conn.cursor()
cursor.execute("SELECT * FROM employee_table WHERE user_id='%s'" % self.id)
result = cursor.fetchone()
conn.close()
self.query_result.emit(result) # 发送查询结果信号
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.query_thread = None # 查询线程
def read_data(self):
data = self.ser.readline()
if data:
id = data.decode().strip()
if not self.query_thread: # 如果查询线程不存在,则创建并启动
self.query_thread = QueryThread(id)
self.query_thread.query_result.connect(self.update_ui)
self.query_thread.start()
else:
self.query_thread.id = id # 如果查询线程已存在,则更新查询ID
QTimer.singleShot(100, self.read_data)
def update_ui(self, result):
if result:
self.id_label.setText("员工ID:" + result[0])
self.name_label.setText("姓名:" + str(result[1]))
self.six_label.setText("性别:" + result[2])
self.sfz_label.setText("身份证:" + str(result[3]))
self.tel_label.setText("电话:" + result[4])
else:
self.id_label.setText("员工ID:")
self.name_label.setText("姓名:")
self.six_label.setText("性别:")
self.sfz_label.setText("身份证:")
self.tel_label.setText("电话:")
def closeEvent(self, event):
self.ser.close()
if self.query_thread:
self.query_thread.quit()
self.query_thread.wait()
```
阅读全文