You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python通过EasyModbus读取PLC数据存入PostgreSQL遇类型错误求助

PLC数据存入PostgreSQL时的数据类型错误

我想要将PLC的数据保存至PostgreSQL数据库,编写了如下Python代码:

#!/usr/bin/env python
'''
Created on 12.09.2016
@author: Stefan Rossmann
'''
# @UnresolvedImport
from easymodbus.modbusClient import *
# @UnresolvedImport
import psycopg2
conn = psycopg2.connect(host="127.0.0.1",
                        port="5432",
                        user="americo",
                        password="123456",
                        database="rapidscada")
modbusClient = ModbusClient('192.168.5.1', 502)
#modbusClient = ModbusClient('COM4')
modbusClient.connect()
#discreteInputs = modbusClient.read_discreteinputs(3, 1)
holding_registers = modbusClient.read_holdingregisters(3, 1)
print (holding_registers)
cursor = conn.cursor()
cursor.execute("INSERT INTO mitablita (datito, detalle) VALUES(%s, %s)", (holding_registers, 'tg1010_2'))
conn.commit() # <- We MUST commit to reflect the inserted data
cursor.close()
conn.close()
modbusClient.close()

运行代码时出现数据类型错误,我很困惑,因为待保存的数据与数据库表字段均为整数类型。


解决方案

问题根源在于read_holdingregisters的返回值:该方法无论读取多少个寄存器,返回的都是列表类型。哪怕你只读取1个寄存器,它也会返回类似[123]的列表,而非单个整数。而数据库字段datito是整数类型,直接传入列表就会触发类型不匹配错误。

只需要取列表的第一个元素即可解决问题:

# 修改插入语句,传入列表中的单个整数
cursor.execute("INSERT INTO mitablita (datito, detalle) VALUES(%s, %s)", (holding_registers[0], 'tg1010_2'))

你也可以在插入前打印变量类型,确认数据格式:

print(type(holding_registers))  # 输出 <class 'list'>
print(type(holding_registers[0]))  # 输出 <class 'int'>

这样就能确保传入的是单个整数,与数据库字段类型匹配。


内容的提问来源于stack exchange,提问作者user19428866

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:10:29