class DataThread(QThread): valueUpdated = pyqtSignal(float) # 只获取一次串口数据 def run(self): ser = serial.Serial('COM3', 9600) data = ser.readline() if data: # 将字符串按空格分割,并取第三个元素作为数值 value_str = data.decode().strip().split()[1] value = float(value_str) self.valueUpdated.emit(value) ser.close()获取到数据后上传数据库,"INSERT INTO em_salary(user_id,get_time,get_kg) VALUES (%s,NOW(),%s)" % (self.id, str(self.value))根据输入的ID
时间: 2024-02-05 19:12:58 浏览: 167
,可以将代码修改为以下形式:
```
import mysql.connector
from mysql.connector import Error
import serial
from PyQt5.QtCore import QThread, pyqtSignal
class DataThread(QThread):
valueUpdated = pyqtSignal(float)
def __init__(self, id):
super().__init__()
self.id = id
def run(self):
try:
# 打开数据库连接
connection = mysql.connector.connect(host='localhost', database='test', user='root', password='password')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL database... MySQL Server version on ", db_Info)
ser = serial.Serial('COM3', 9600)
data = ser.readline()
if data:
# 将字符串按空格分割,并取第三个元素作为数值
value_str = data.decode().strip().split()[2]
value = float(value_str)
self.valueUpdated.emit(value)
# 插入数据到数据库
cursor = connection.cursor()
insert_query = "INSERT INTO em_salary(user_id, get_time, get_kg) VALUES (%s, NOW(), %s)"
insert_values = (self.id, str(value))
cursor.execute(insert_query, insert_values)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into em_salary table")
except Error as e:
print("Error while connecting to MySQL", e)
finally:
# 关闭数据库连接和串口连接
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
ser.close()
```
其中,我们新增了一个 `id` 参数,用于指定插入数据的用户 ID。在 `run()` 方法中,我们首先连接到 MySQL 数据库,并获取串口数据。然后,我们将第三个元素作为数值,并通过信号 `valueUpdated` 将其传递给主线程。最后,我们将数据插入到数据库表中。
请注意,在此处我们使用了 `mysql-connector-python` 库来连接到 MySQL 数据库。如果您尚未安装该库,请使用以下命令进行安装:
```
pip install mysql-connector-python
```
阅读全文