You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Digi HP900 RF模块MySQL插入数据异常,求排查代码语法问题

代码问题排查与修正

核心问题梳理

你的代码存在语法错误、逻辑错误和SQL参数传递错误,导致无法正确读取XBee数据并插入MySQL,以下是具体问题和修复方案:


1. 字符串语法错误

print(" + +") 这种换行写法不符合Python语法,Python中多行字符串需用三引号包裹或字符串拼接。

修复示例:

print("+" + "-"*36 + "+")
print(" | XBee Python Library Receive Data Sample |")
print("+" + "-"*36 + "+")

2. 缩进错误

Python是缩进敏感语言,main()函数内的所有代码、try块内的代码、data_receive_callback函数定义都未正确缩进,会直接触发IndentationError。

修复规则:

  • main()内的代码统一缩进4个空格
  • try块内的代码缩进4个空格
  • data_receive_callback作为内部函数,需缩进在try块内

3. SQL语句与参数传递错误

你的INSERT语句存在两处致命错误:

  • VALUES子句格式错误,多了冗余括号(xbee_message)
  • 直接传入xbee_message对象而非解码后的字符串,参数传递方式完全错误

正确写法:
需将XBee消息的解码数据作为参数传入execute()的第二个参数列表,同时要先判断xbee_message不为空:

if xbee_message:
    temp_data = xbee_message.data.decode()
    cur.execute(
        "INSERT INTO dbtable (`post_id`, `tempdata`, `split0`, `status`, `lastupdate`, `text`, `content`, `likes`) "
        "VALUES ('1', %s, 'split0', '2', CURRENT_TIMESTAMP, 'mynkey', 'joe', 'hello')",
        (temp_data,)
    )

4. 数据接收逻辑错误

你同时使用回调函数和read_data()一次性读取,且read_data()仅执行一次,大概率会因未收到数据返回None,导致插入失败。正确逻辑二选一:

  • 在回调函数中处理数据库插入(实时接收数据时触发)
  • 循环调用read_data()等待数据

推荐用回调方式,适配XBee异步实时接收的场景。

5. 数据库连接逻辑问题

当前代码打开设备后立刻连接数据库,无论是否收到数据都执行插入,且连接后直接关闭。应在收到数据时再处理数据库操作,同时添加异常处理避免操作失败导致程序崩溃。


修正后的完整代码

import mysql.connector
from digi.xbee.devices import XBeeDevice

PORT = "/dev/ttyUSB1"
BAUD_RATE = 115200

def main():
    print("+" + "-"*36 + "+")
    print(" | XBee Python Library Receive Data Sample |")
    print("+" + "-"*36 + "+")

    device = XBeeDevice(PORT, BAUD_RATE)
    db_connection = None

    def data_receive_callback(xbee_message):
        nonlocal db_connection
        try:
            # 解码XBee收到的数据
            received_data = xbee_message.data.decode()
            print(f"From {xbee_message.remote_device.get_64bit_addr()} >> {received_data}")

            # 数据库插入操作
            if not db_connection or not db_connection.is_connected():
                db_connection = mysql.connector.connect(
                    host='localhost',
                    database='dbcapture',
                    user='root',
                    password='XXXX'
                )
            cur = db_connection.cursor()
            cur.execute(
                "INSERT INTO dbtable (`post_id`, `tempdata`, `split0`, `status`, `lastupdate`, `text`, `content`, `likes`) "
                "VALUES ('1', %s, 'split0', '2', CURRENT_TIMESTAMP, 'mynkey', 'joe', 'hello')",
                (received_data,)
            )
            db_connection.commit()
            cur.close()
            print("数据插入成功")
        except Exception as e:
            print(f"处理失败: {str(e)}")
            if db_connection:
                db_connection.rollback()

    try:
        device.open()
        device.add_data_received_callback(data_receive_callback)
        print("等待数据...\n")
        input("按回车键退出程序\n")
    finally:
        if db_connection and db_connection.is_connected():
            db_connection.close()
        if device is not None and device.is_open():
            device.close()

if __name__ == '__main__':
    main()

额外注意事项

  • 确保MySQL的dbtable表结构与插入字段完全匹配,尤其是tempdata字段类型需支持存储字符串
  • 替换代码中的password='XXXX'为你的MySQL真实密码
  • 如果XBee传输二进制数据,需根据实际编码调整decode()参数(如decode('utf-8'))

内容的提问来源于stack exchange,提问作者MYNeighborhood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:24:11