首页 > 解决方案 > 如何在 NodeJS 中使用变量插入查询

问题描述

我有一个查询,但我不确定如何允许 NodeJS 使用变量输入它。我该如何实现?什么是最好的方法?

var sql = (
    "INSERT INTO stats_tmp (
        id, 
        timestamp, 
        campaign_nm, 
        calls, 
        seconds, 
        answered, 
        failure, 
        dnc, 
        amd, 
        transfers, 
        transfer_seconds, 
        cost
    ) VALUES (" 
        + estarr[0].id + ", " 
        + estarr[0].timestamp + ", " 
        + estarr[0].name + ", " 
        + estarr[1].calls + ", " 
        + estarr[1].seconds + ", " 
        + estarr[1].answers + ", " 
        + estarr[1].failures + ", " 
        + estarr[1].dncs + ", " 
        + estarr[1].amd + ", " 
        + estarr[1].transfers + ", " 
        + estarr[1].transfers + ", " 
        + estarr[1].transferseconds + ", "
        + estarr[1].cost 
    + ")"
);

标签: mysqlnode.js

解决方案


您想使用准备好的语句。

考虑:

var query = connection.query(
    'INSERT INTO stats_tmp (
        id, 
        timestamp, 
        campaign_nm, 
        calls, 
        seconds, 
        answered, 
        failure, 
        dnc, 
        amd, 
        transfers, 
        transfer_seconds, 
        cost
    ) VALUES (
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?
    )',
    [
        estarr[0].id,
        estarr[0].timestamp,
        estarr[0].name,
        estarr[1].calls,
        estarr[1].seconds,
        estarr[1].answers,
        estarr[1].failures,
        estarr[1].dncs,
        estarr[1].amd,
        estarr[1].transfers,
        estarr[1].transfers,
        estarr[1].transferseconds,
        estarr[1].cost
    ],
    function(err, results) {    
      ...
});

推荐阅读