【问题标题】:Data not getting stored in mysql using python mysql.connector数据未使用 python mysql.connector 存储在 mysql 中
【发布时间】:2019-10-17 06:04:46
【问题描述】:

我正在从我的 python 脚本连接到 MySQL,订阅来自 mqtt 代理的主题,并且每当我收到数据时,我都会存储数据。

代码

import mysql.connector
connection = mysql.connector.connect(host='localhost',database='db',user='',
                                   password='',auth_plugin='mysql_native_password')

sql_insert_query = """      #INSERT query
cursor = connection.cursor()

def on_message(client, userdata, message):
    print("message received ")
    msg = json.loads(message.payload.decode("utf-8"))
    #processing of message

    cursor.execute(sql_insert_query,processed_msg)
    connection.commit()
    print('inserted in db')

def on_connect(client, userdata, flags, rc): 
    print("Subscribing to topic","topic")
    client.subscribe("topic")

broker_address=""
port = 8888

client = mqtt.Client(clean_session=True) #create new instance
client.on_connect = on_connect
client.on_message = on_message #attach function to callback

print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
client.loop_forever() #stop the loop

因此,当 mqtt 收到任何消息时,使用此代码保存数据。但是有时 mqtt 超过 8 小时没有收到数据,然后又开始接收数据。在这种情况下,脚本不会存储 8 小时左右后的数据。我相信某种超时正在发生。因为当我再次运行脚本时,数据存储在 mysql db 中。有人可以帮我理解这是什么类型的超时或如何解决这个问题吗?

谢谢

【问题讨论】:

  • 您在顶部连接一次到数据库可能连接超时您每次收到消息时连接到数据库并在您的 on_message 回调中完成时关闭
  • 谢谢!!知道可能是什么原因
  • on_message回调中围绕数据库更新代码添加一个try/expect块。这将向您显示错误,因为 MQTT 客户端在其自己的 try/expect 块中调用了 on_message 函数,该块丢弃了所有抛出的异常。

标签: python mysql mqtt mysql-python paho


【解决方案1】:

您在顶部连接一次数据库,可能连接超时

您每次收到消息时连接到数据库,并在您的 on_message 回调中完成时关闭

原因:连接超时

您可以通过

将超时设置为更长的时间
'SET GLOBAL connect_timeout=86400';
'SET GLOBAL wait_timeout=86400';
'SET GLOBAL interactive_timeout=86400'; 

或者干脆不这样做,你可以在on_message回调中这样做

def on_message(client, userdata, message):
    connection = mysql.connector.connect(host='localhost',database='db',user='',
    cursor = connection.cursor()                                   
    print("message received ")
    msg = json.loads(message.payload.decode("utf-8"))
    #processing of message

    cursor.execute(sql_insert_query,processed_msg)
    connection.commit()
    cursor.close()
    connection.close()
    print('inserted in db')

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 2017-12-10
    • 1970-01-01
    • 2015-07-14
    • 2016-06-17
    • 1970-01-01
    • 2017-03-11
    • 2021-03-16
    • 2019-10-25
    相关资源
    最近更新 更多