我想使用 Node.js 将 API 数据存储在 SQL Server 数据库中。正如您在下面的第一个代码中看到的那样,它已经适用于普通的 INSERT 查询。
server.route({
method: 'POST',
path: '/',
handler: async(request, h) => {
try {
await pool.query("INSERT INTO mytable(device,data,stationId,rssi,unix_timestamp) VALUES('"+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';
}
}
});
现在我想稍微改进一下代码以避免 SQL 注入并获得更好的概览。
因此,我想使用本文档中描述的准备好的语句:https ://www.npmjs.com/package/mssql#prepared-statement
到目前为止,我已经在这里做到了:
server.route({
method: 'POST',
path: '/',
handler: async(request, h) => {
const ps = new sql.PreparedStatement(pool)
try {
ps.input('device', sql.VarChar(10))
ps.input('data', sql.VarChar(24))
ps.input('station', sql.NChar(10))
ps.input('rssi', sql.Float)
ps.input('time', sql.Int)
await ps.prepare('INSERT INTO mytable(device,data,stationId,rssi,unix_timestamp) VALUES(@device,@data,@station,@rssi,@time)');
try {
await ps.execute(
{ device: request.payload.device },
{ data: request.payload.data },
{ station: request.payload.station },
{ rssi: request.payload.rssi },
{ time: request.payload.time }
)
} finally {
await ps.unprepare();
}
return h.response('Callback received').code(200);
}
catch (err) {
console.log("SQL Err", err.stack);
return 'Error';
}
}
});
并出现以下错误:
at Parser.emit (events.js:223:5)
at Parser.<anonymous> (C:\Users\AW\sqltest\node_modules\tedious\lib\token\token-stream-parser.js:37:14)
at Parser.emit (events.js:223:5)
at addChunk (C:\Users\AW\sqltest\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\Users\AW\sqltest\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\Users\AW\sqltest\node_modules\readable-stream\lib\_stream_readable.js:240:10)
at Parser.Transform.push (C:\Users\AW\sqltest\node_modules\readable-stream\lib\_stream_transform.js:139:32)
这是我从 API 获得的 JSON 数据示例:
{
"device":"887B53",
"data":"4660000000000062b4a8",
"station":"1B2C"
"rssi":"-123",
"time":"1585258718"
}
我希望有人可以帮助我。