florinstefan8830
florinstefan8830

Reputation: 55

Why do i get parse error when i want to make an mysql insert with nodejs

I have an sql insert and I recive the following error:

 code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''CR0001'' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "INSERT INTO coordonate (id_scooter,lat,longi,alt,ip,port,speed,nr_satelites,battery_lvl) VALUES 'CR0001' "

my code is:

var insert = "INSERT INTO coordonate (id_scooter,lat,longi,alt,ip,port,speed,nr_satelites,battery_lvl) VALUES  ?  ";

      con.query(insert, [array[0],array[3],array[4],array[5],rinfo.address,rinfo.port,array[6],array[2],array[1]], function (err, result) {
        if (err) throw err;

Upvotes: 0

Views: 490

Answers (1)

Jonathan Irvin
Jonathan Irvin

Reputation: 1062

You are only passing in a single array. When you insert, it needs to be an array of arrays wrapped in an array, like this:

var insert = "INSERT INTO coordonate (id_scooter,lat,longi,alt,ip,port,speed,nr_satelites,battery_lvl) VALUES  ?  ";

con.query(insert, [ [ [array[0],array[3],array[4],array[5],rinfo.address,rinfo.port,array[6],array[2],array[1]] ] ], function (err, result) {
  if (err) throw err;
});

Notice the two extra [ before and two extra ] after your data in the query.

[ [ [array[0],array[3],array[4],array[5],rinfo.address,rinfo.port,array[6],array[2],array[1]] ] ]

As an alternative, if you want to only insert a single row, you could do something like this, and pass in a JSON object:

var insert = "INSERT INTO coordonate SET ? ";

con.query(insert, { id_scooter: array[0], lat: array[3], longi: array[4], alt: array[5], ip: rinfo.address, port: rinfo.port, speed: array[6], nr_satelites: array[2], battery_lvl: array[1] }, function (err, result) {
  if (err) throw err;
});

Upvotes: 3

Related Questions