如何在带有变量的NodeJS中插入查询

时间:2019-10-14 21:05:50

标签: mysql node.js

我有一个查询,但是我不确定如何允许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 
    + ")"
);

1 个答案:

答案 0 :(得分:0)

您要使用准备好的语句。

考虑:

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) {    
      ...
});