Parametized INSERT query with node-mssql

坚强是说给别人听的谎言 提交于 2020-04-16 05:48:31

问题


I want to parametrize an insert query with node.js for SQL Server. Unfortunately it will not work and I don't really know if it's a Node module issue or a syntax failure.

Code:

server.route({
    method: 'POST',
    path: '/',
    handler: async (request, h) => {

    try {
        await pool.query("INSERT INTO sigfoxmessages(device,data,station,rssi,unix_timestamp) VALUES($1,$2,$3,$4,$5))"
        [request.payload.device, request.payload.data, request.payload.station, request.payload.rssi, request.payload.time]);

        return h.response('Callback received').code(200);
    }
    catch (err) {
        console.log("SQL Err", err.stack);
        return 'Error';
    }
  }
});

Error:

at exports.Manager.execute (C:\Users\A\sqltest\node_modules@hapi\hapi\lib\toolkit.js:60: 33)
at Object.internals.handler (C:\Users\A\sqltest\node_modules@hapi\hapi\lib\handler.js:46 :48)
at exports.execute (C:\Users\A\sqltest\node_modules@hapi\hapi\lib\handler.js:31:36)
at Request._lifecycle (C:\Users\A\sqltest\node_modules@hapi\hapi\lib\request.js:365:68)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async Request._execute (C:\Users\A\sqltest\node_modules@hapi\hapi\lib\request.js:274: 9)

Used node modules:

  • hapi/hapi 19.0.5
  • mssql: 6.0.1

Does anyone have an idea or or a suggestion?


回答1:


According to the documentation for mssql you can use es6 template literals in you INSERT statement.

pool.query`INSERT INTO sigfoxmessages (device,data,station,rssi,unix_timestamp) VALUES(${request.payload.device}, ${request.payload.data}, ${request.payload.station}, ${request.payload.rssi}, ${request.payload.time}))`

Docs: https://www.npmjs.com/package/mssql



来源:https://stackoverflow.com/questions/61065500/parametized-insert-query-with-node-mssql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!