节点红色sql节点上的SQL语法

问题描述 投票:0回答:1

数据已从Arduino通过串口传递到node-red,数据被格式化为json。在node-red中可以从json中获取数据。然后它会被传递到一个函数节点以格式化为 SQL 查询,以便将其添加到数据库中。

SQL节点来自node-red-node-mysql。

节点红色函数

[
    {
        "id": "2d4f4e57.8fda6a",
        "type": "function",
        "z": "5b88858e4e0520c4",
        "name": "Format SQL query",
        "func": "// Set the table name and fields\nvar tableName = \"sensordata\";\nvar fields = [\"rpm\", \"water\", \"temp\", \"humidity\"];\n\n// Create the SQL query string\nvar values = [];\nfields.forEach(function(field) {\n    values.push(msg.payload[field]);\n});\nvar sqlQuery = \"INSERT INTO \" + tableName + \" (\" + fields.join(\",\") + \") VALUES (\" + values.join(\",\") +\")\";\n\n// Store the SQL query in the message payload\nmsg.topic = \"INSERT INTO sensordata\";\nmsg.payload = sqlQuery;\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 850,
        "y": 200,
        "wires": [
            [
                "712c1b95.f32b98",
                "f289552cbe4f28ea"
            ]
        ]
    }
]

函数中的js

// Set the table name and fields
var tableName = "sensordata";
var fields = ["rpm", "water", "temp", "humidity"];

// Create the SQL query string
var values = [];
fields.forEach(function(field) {
    values.push(msg.payload[field]);
});
var sqlQuery = "INSERT INTO " + tableName + " (" + fields.join(",") + ") VALUES (" + values.join(",") +")";

// Store the SQL query in the message payload
msg.topic = "INSERT INTO sensordata";
msg.payload = sqlQuery;
return msg;

部分arduino代码

StaticJsonDocument<200> jsonDoc;
        jsonDoc["rpm"] = rpm;
        jsonDoc["water"] = Water;
        jsonDoc["temp"] = temp;
        jsonDoc["humidity"] = hum;
       
    
        // Serialize the JsonObject to a string
        char jsonString[200];
        serializeJson(jsonDoc, jsonString);
    
        // Print the JSON string to the serial monitor
        Serial.println(jsonString);

我尝试在 phpmyadmin 上单独运行查询,它可以工作,但是当我运行流程时,它不会通过。

错误

错误:您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本对应的手册,了解在第 1 行 '' 附近使用的正确语法

json数据

{"rpm":223.2857,"water":0,"temp":27.9,"humidity":46}

查询

INSERT INTO sensordata (rpm, water, temp, humidity)
VALUES (223.2857, 0, 27.9, 46)

我想要将数据添加到数据库中。

sql node.js arduino mariadb node-red
1个回答
0
投票

将有效负载更改为主题

// Store the SQL query in the message payload
msg.topic = sqlQuery;
return msg;
© www.soinside.com 2019 - 2024. All rights reserved.