最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

为什么我的sql多行插入查询包含语法错误?

运维笔记admin12浏览0评论

为什么我的sql多行插入查询包含语法错误?

为什么我的sql多行插入查询包含语法错误?

我正在用heroku上的nodejs处理一个发布请求,并尝试将json插入一个postgres数据库中。

const client = await pool.connect();
    var jsondata = req.body;
    var values = [];
    for(var i=0; i< jsondata.length; i++) {
                         values.push([jsondata[i].id,jsondata[i].title,jsondata[i].imageUrl,jsondata[i].orderPosition]);
                    }
const sqlQuery = 'INSERT INTO showme_gardens_tourMapTableTest (mapId, imageId, title, position) VALUES ?;';
console.log("$%$% " + values);                  
const  resultOfMapsInsert = await client.query(sqlQuery, [values]);

我收到语法错误

2019-10-15T13:08:35.238210+00:00 app[web.1]: $%$% 25,Wind in the willows,,4
2019-10-15T13:08:35.244196+00:00 app[web.1]: { error: syntax error at or near "?"
2019-10-15T13:08:35.244199+00:00 app[web.1]: at Connection.parseE (/app/node_modules/pg/lib/connection.js:602:11)
2019-10-15T13:08:35.244202+00:00 app[web.1]: at Connection.parseMessage (/app/node_modules/pg/lib/connection.js:399:19)
2019-10-15T13:08:35.244204+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/pg/lib/connection.js:121:22)
2019-10-15T13:08:35.244206+00:00 app[web.1]: at Socket.emit (events.js:198:13)
2019-10-15T13:08:35.244208+00:00 app[web.1]: at addChunk (_stream_readable.js:288:12)
2019-10-15T13:08:35.244210+00:00 app[web.1]: at readableAddChunk (_stream_readable.js:269:11)
2019-10-15T13:08:35.244212+00:00 app[web.1]: at Socket.Readable.push (_stream_readable.js:224:10)
2019-10-15T13:08:35.244214+00:00 app[web.1]: at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
2019-10-15T13:08:35.244216+00:00 app[web.1]: name: 'error',
2019-10-15T13:08:35.244218+00:00 app[web.1]: length: 90,
2019-10-15T13:08:35.244220+00:00 app[web.1]: severity: 'ERROR',
2019-10-15T13:08:35.244222+00:00 app[web.1]: code: '42601',
回答如下:

您需要将值包装在括号中。

尝试:

const sqlQuery = 'INSERT INTO showme_gardens_tourMapTableTest (mapId, imageId, title, position) VALUES ('+values+');';
const  resultOfMapsInsert = await client.query(sqlQuery, values.join(","));

或者您也可以这样做:

const sqlQuery = 'INSERT INTO showme_gardens_tourMapTableTest (mapId, imageId, title, position) VALUES ($1, $2, $3);'
const  resultOfMapsInsert = await client.query(sqlQuery, [values]);
发布评论

评论列表(0)

  1. 暂无评论