【问题标题】:Using DATEADD in SQL INSERT query with hapi.js在带有 hapi.js 的 SQL INSERT 查询中使用 DATEADD
【发布时间】:2020-07-18 06:18:54
【问题描述】:

我想使用 Node.js 将 unix 时间戳(包含在收到的 Json 正文中)作为人类可读的时间导入我的 MSSQL 数据库。因此,我直接在插入查询中转换了请求对象。我在 SQL Server 中设置了数据类型“datetime”。

Json 主体如下所示:


{
  "device":"887B53",
  "data":"4660000000000062b4a8",
  "station":"1B2C",
  "rssi":"-123",
  "time":"1586096200"
} 

我使用 hapi 服务器进行路由:

  server.route({

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

            try {

                const datetime = DATEADD(ss, request.payload.time, '19700101');

                await pool.query("INSERT INTO mytable(timestamp)VALUES('"+datetime+"')");

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

        }

    });

起初它完全按照我的预期工作。但比我搞砸了一些东西,它不再起作用了。我完全不知道发生了什么,也找不到问题。

抛出此错误:

在 Request._lifecycle (C:\Users\AW\sqltest\node_modules@hapi\hapi\lib\request.js:365:68)
在 processTicksAndRejections (internal/process/task_queues.js:94:5)
在异步 Request._execute (C:\Users\AW\sqltest\node_modules@hapi\hapi\lib\request.js:274:9)

【问题讨论】:

    标签: node.js sql-server tsql datetime sql-insert


    【解决方案1】:

    大概,您希望dateadd() 查询中而不是在 javascript 中。比如:

    try {
        const request = pool.request()
        request.input('mytimestamp', sql.VarChar, request.payload.time)
        await request.query(
            "INSERT INTO mytable(timestamp) VALUES(DATEADD(ss, @mytimestamp, '19700101'))"
        );
        return h.response('Callback received').code(200);
    }
    

    请注意,这使用了参数化查询,而不是将参数混杂到查询字符串中 - 这既安全又高效。

    【讨论】:

    • 参数化过程是否也可以使用 MSSQL-Node。不幸的是我仍然得到一个错误。这也可能是一个 hapi 问题。
    • @Karol-Kahn:请查看我编辑的答案。这在 MSSQL / Node 中有效吗?
    • 不幸的是:/```:48) 在exports.execute (C:\Users\Artur\sqltest\node_modules\@hapi\hapi\lib\handler.js:31:36) 在Request._lifecycle (C:\Users\Artur\sqltest\node_modules\@hapi\hapi\lib\request.js:365:68) 在 processTicksAndRejections (internal/process/task_queues.js:94:5) at async Request._execute (C:\Users\Artur\sqltest\node_modules\@hapi\hapi\lib\request.js:274: 9)´´´ 我开了一个新问题。在那里你可以从代码中看到更多。请求对象已被使用。 stackoverflow.com/questions/61065500/…
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多