我正在尝试将值放入SQL Server上的数据库表中。
我的程序将订阅MQTT服务器,每当收到消息时,它都会将消息放入数据库表中。
以下是我的代码:
import paho.mqtt.client as mqtt
import signal
import sys
import pymssql
from os import getenv
from time import gmtime, strftime
#Signal Handler
def signal_handler(signal, frame):
print("\nProgram has been interrupted!")
sys.exit(0)
#MQTT Subscribe ON_CONNECT
def on_connect(client, userdata, flags, rc):
if str(rc) == '0':
print ("Connected Successfully")
else:
print ("Connection has a problem")
#CLIENT SUBSCRIPTION
client.subscribe("topic1")
#MQTT Subscribe ON_MESSAGE
def on_message(client, userdata, msg):
print("[" + msg.topic + "] " + str(msg.payload) )
deviceID = msg.payload
time = strftime("%Y%m%d%H%M%S", gmtime())
#Puts the data into the SQL Server DB Table "Topic"
cursor.execute("""
IF OBJECT_ID('Topic', 'U') IS NOT NULL
DROP TABLE Topic
CREATE TABLE Topic(
id INT NOT NULL,
deviceID INT NOT NULL,
dateTime INT NOT NULL,
PRIMARY KEY(id)
)
""")
cursor.execute(
"INSERT INTO Topic VALUES (%d)",
[(id, deviceID, time)]
conn.commit()
#Signal Handler
signal.signal(signal.SIGINT, signal_handler)
#Connect to the SQL Server
server = 'mqtt.server.address.com'
user = 'sa'
password = 'pwd'
database = 'topics'
#SQL Server Connection Established
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()
#Establishing MQTT Subscribe Connection
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mqtt.server.address.com", 1883, 60)
client.loop_forever()
我收到了以下错误:
提前感谢您的帮助。
答案 0 :(得分:2)
您应该将错误直接发布在问题中。
错误清楚地表明query_params
参数应该是一个
元组或字典而不是列表。
cursor.execute("INSERT INTO Topic VALUES (%d)",
[(id, deviceID, time)])
您正在尝试将包含一个元组的列表插入到单个列中。
另请注意,您在此行中错过了结束)
。
相反,您应该单独插入每个列,并使用元组作为参数:
cursor.execute("INSERT INTO Topic VALUES (%d, %d, %d)",
(id, deviceID, time))