Я настраиваю новый сервер с python для получения данных из облачного брокера MQTT. Я хочу, чтобы мой код мог отправлять несколько данных в БД MYSQL из разных тем, и все данные помещались в разные столбцы. Но, мой код только может отправлять данные в один столбец сейчас. Как это исправить? Вот мой код
enter code here
#!/usr/bin/env python 1
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import sys
import MySQLdb
# Koneksi ke database
try:
db = MySQLdb.connect("127.0.0.1","root","","mqtt")
except:
print("Failed to connect to Database")
print("Stop...")
sys.exit()
# Prepare cursor
cursor = db.cursor()
# The callback for when the client receives a CONNACK response from the
server.
def on_connect(client, userdata, flags, rc):
print("Connected: "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("Current_Temperatur")
client.subscribe("Current_Humidity")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
lista = msg.topic
sql = """INSERT INTO `mqtt`.`table` (`id`, `topic`, `sensor`, `date`)
VALUES (NULL, '""" + lista + """','""" + str(msg.payload) + """',
CURRENT_TIMESTAMP);"""
try:
# save to mySQL
cursor.execute(sql)
db.commit()
print("Save to Database ... OK")
except:
db.rollback()
print("Save to Database ... Failed")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
try:
client.connect("m16.cloudmqtt.com", 13959, 60)
except:
print("Couldn't connect to MQTT Broker...")
print("stop...")
sys.exit()
client.username_pw_set("asjsacsdjkc", "2121324352322")
try:
client.loop_forever()
except KeyboardInterrupt: #ctrl+C
print("Stop...")
db.close()