python - 数据未使用 python mysql.connector 存储在 mysql 中

标签 python mysql mqtt mysql-python paho

我正在从我的 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 数据库中。谁能帮我理解这是什么类型的超时或如何解决这个问题?

谢谢

最佳答案

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

每次收到消息时连接到数据库,并在 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')

关于python - 数据未使用 python mysql.connector 存储在 mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425917/

相关文章:

Python Mechanize : UnboundLocalError: local variable 'f' referenced before assignment

php - opencart 1.4.9.3 mysql 未知列报错

azure - IotHubClientTransientException : Transient error occured, 请重试

python - 使用 nlp/spacy 查找相似之处

python - 无法替换 json 对象中的参数值

python - 如何从 np.datetime64 对象中获取月份,而不是使用 pandas

mysql - Perl 脚本无法在 @INC 中找到 Text/Template.pm

mysql - 如何在使用 UNION 的查询中实现 SQL_CALC_FOUND_ROWS?

node.js - Node js setinterval 在连接时无法与 mqtt 客户端一起使用

ios - 构建 iOS 项目得到架构 i386 错误的重复符号