SQL 语法错误 [node-red 中的函数]

Error in SQL syntax [function in node-red]

我正在尝试通过 node-red post 将数据导入数据库,但出现此错误。

"Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into customizations(custom_id, product_id, paper_id, ribbon_id, custom_qt' at line 1"

这是我用的函数

var items    = msg.payload.items;
var sql = "";
var template = "insert into customizations(custom_id, product_id, paper_id, ribbon_id, custom_qty, message)";
template    += " values(null,'c1','c2','c3','c4','c5')";

for(var i=0;i<items.length;i++){
var cp = template;
cp = cp.replace('c1',items[i].autoId);
cp = cp.replace('c2',items[i].paper_id);
cp = cp.replace('c3',items[i].ribbon_id);
cp = cp.replace('c2',items[i].qty);
cp = cp.replace('c3',items[i].message);
sql += cp;
}


msg.topic = sql;
return msg;

值后通常会有一个 space,但这可能无关紧要。您将 c2 和 c3 替换两次。使用 bind variables 而不是文本插值。如果消息等任何字段包含引号,它会为您转义:

connection.query('insert into customizations(product_id, paper_id, ribbon_id, custom_qty, message) values (?, ?, ?, ?, ?)', [items[i].autoId, items[i].paper_id, items[i].ribbon_id, items[i].qty, items[i].message], ...)
  1. 使用替换或任何字符串操作向您的 SQL 插入值是极其糟糕的习惯。阅读您的手册以了解如何 PREPARE 语句一次,然后在循环中执行准备好的语句。
  2. 您在替换部分混合了 c2c3c4c5
  3. 您的语法错误是 SQL 语句应以分号结尾 (;)