繁体   English   中英

绑定消息提供 1 个参数,但准备好的语句“”需要 2 个

[英]Bind message supplies 1 parameters, but prepared statement "" requires 2

我有一个包含两列id jsonb primary_keyname的数据库goods 使用此查询:

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)
});

编辑2:

使用以下内容:

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]

根据docs ,参数必须是 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"];

我在使用 slonik 时遇到了同样的问题。

不要使用插值

不要这样做!

connection.query(sql`
  SELECT 1
  FROM foo
  WHERE bar = ${baz}
`);

使用值占位符

这样做 - 用单引号包裹变量

connection.query(sql`
  SELECT 1
  FROM foo
  WHERE bar = ${'baz'}
`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM