Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a database goods with two columns id jsonb primary_key and name. Using this query:

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

together with the following data:

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

gives me the following error:

{ [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' }

I have a postgres database set up, connected via pg.Pool() and executing javascript to insert my data.

Edit: This is how I prepare my query:

pool.query(query, [data]).then(() => {
    console.log("ok")
})
.catch(error => {
    console.log(error)
});

Edit2:

Using the following:

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

Just spits out the following error: [TypeError: self.values.map is not a function]

like image 612
optional Avatar asked May 03 '17 08:05

optional


2 Answers

As per docs, parameters must be JavaScript object (which is array). So you don't need to stringify data

Try this:

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

const data = [1, "milk"];

pool.query(query, data).then(....)

Or

pool.query({ 
    text: 'INSERT INTO goods (id, name) VALUES ($1, $2)', 
    values: [1, 'milk']
 }).then(...)
like image 86
Priyesh Kumar Avatar answered Oct 31 '22 07:10

Priyesh Kumar


As per documentation, a Prepared Statement expects an array of values, not an object with properties, i.e. your data must be: const data = [1, "milk"];

like image 2
vitaly-t Avatar answered Oct 31 '22 08:10

vitaly-t