绑定消息提供1个参数,但是准备好的语句“”需要2个参数
我有一个数据库goods
两列id jsonb primary_key
和name
。 使用这个查询:
const query = 'INSERT INTO "goods" (id, name) VALUES ($1, $2)'
连同以下数据:
const data = {id: 1, name: "milk"};
给我以下错误:
{ [error: bind message supplies 1 parameters, but prepared statement "" requires 2] name: 'error', length: 130, severity: 'ERROR', code: '08P01', detail: undefined, hint: undefined, position: undefined, internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'postgres.c', line: '1556', routine: 'exec_bind_message' }
我有一个postgres数据库设置,通过pg.Pool()连接并执行JavaScript来插入我的数据。
编辑:这是我如何准备我的查询:
pool.query(query, [data]).then(() => { console.log("ok") }) .catch(error => { console.log(error) });
EDIT2:
使用以下内容:
const query = 'INSERT INTO "goods" (id, name) VALUES ($1, $2)' const data = JSON.stringify([1, "milk"]); pool.query(query, data).then(() => { console.log("ok") }) .catch(error => { console.log(error) });
只是吐出以下错误: [TypeError: self.values.map is not a function]
根据文档 ,参数必须是JavaScript对象(这是数组)。 所以你不需要将data
串联起来
尝试这个:
const query = 'INSERT INTO goods (id, name) VALUES ($1, $2)' const data = [1, "milk"]; pool.query(query, data).then(....)
要么
pool.query({ text: 'INSERT INTO goods (id, name) VALUES ($1, $2)', values: [1, 'milk'] }).then(...)
根据文档 ,Prepared Statement需要一个值的数组,而不是一个具有属性的对象,即你的数据必须是: const data = [1, "milk"];