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

pxyaymoc  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(4)|浏览(291)

我有一个数据库goods,其中有两列id jsonb primary_keyname。使用以下查询:

  1. const query = 'INSERT INTO "goods" (id, name) VALUES ($1, $2)'

字符串
连同下列数据:

  1. const data = {id: 1, name: "milk"};


给了我以下错误:

  1. { [error: bind message supplies 1 parameters, but prepared statement "" requires 2]
  2. name: 'error',
  3. length: 130,
  4. severity: 'ERROR',
  5. code: '08P01',
  6. detail: undefined,
  7. hint: undefined,
  8. position: undefined,
  9. internalPosition: undefined,
  10. internalQuery: undefined,
  11. where: undefined,
  12. schema: undefined,
  13. table: undefined,
  14. column: undefined,
  15. dataType: undefined,
  16. constraint: undefined,
  17. file: 'postgres.c',
  18. line: '1556',
  19. routine: 'exec_bind_message' }


我有一个postgres数据库设置,通过pg.Pool()连接并执行JavaScript来插入我的数据。
编辑:这是我准备查询的方式:

  1. pool.query(query, [data]).then(() => {
  2. console.log("ok")
  3. })
  4. .catch(error => {
  5. console.log(error)
  6. });


编辑2:
使用以下命令:

  1. const query = 'INSERT INTO "goods" (id, name) VALUES ($1, $2)'
  2. const data = JSON.stringify([1, "milk"]);
  3. pool.query(query, data).then(() => {
  4. console.log("ok")
  5. })
  6. .catch(error => {
  7. console.log(error)
  8. });


返回以下错误:[TypeError: self.values.map is not a function]

xwbd5t1u

xwbd5t1u1#

根据文档,参数必须是JavaScript对象(即数组)。因此您不需要对data进行字符串化
试试这个:

  1. const query = 'INSERT INTO goods (id, name) VALUES ($1, $2)'
  2. const data = [1, "milk"];
  3. pool.query(query, data).then(....)

字符串

  1. pool.query({
  2. text: 'INSERT INTO goods (id, name) VALUES ($1, $2)',
  3. values: [1, 'milk']
  4. }).then(...)

展开查看全部
chy5wohz

chy5wohz2#

根据文档,Prepared Statement需要一个值数组,而不是一个具有属性的对象,即您的数据必须是:const data = [1, "milk"];

8qgya5xd

8qgya5xd3#

我的问题是,我把我的占位符值在单引号。
因此,而不是:

  1. const query = {
  2. text: "SELECT email, password from users WHERE email='$1'",
  3. values: [data.email],
  4. };

字符串
这样做:

  1. const query = {
  2. text: "SELECT email, password from users WHERE email=$1", // -> here is the difference
  3. values: [data.email],
  4. };

展开查看全部
knsnq2tg

knsnq2tg4#

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

不要使用插值

别这样

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

字符串

使用值占位符

这样做-用单引号 Package 变量

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

展开查看全部

相关问题