2016-07-14 15 views
0

SQL Server上のデータベースのテーブルに値を入力しようとしています。PYMSSQLを使用して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() 

そして私は、次のエラーを取得されています:事前にあなたの助けを

enter image description here

感謝。

答えて

2
  1. あなたの質問に直接テキストとしてエラーを投稿する必要があります。

  2. このエラーは、query_params引数が
    タプルまたは辞書であり、リストではないことを明確に示唆しています。

    cursor.execute("INSERT INTO Topic VALUES (%d)", 
           [(id, deviceID, time)]) 
    

    1つのタプルを含むリストを1つの列に挿入しようとしています。

    この行には、)の終了がありません。

    代わりにあなたが個別に各列に挿入し、そしてあなたの引数にタプルを使用する必要があります。

    cursor.execute("INSERT INTO Topic VALUES (%d, %d, %d)", 
           (id, deviceID, time)) 
    
関連する問題