简体   繁体   中英

Insterting array as parameter to query in node.js mySQL

I tried searching for this but most results take me to bulk inserts in Node.js which I don't need atm. To my understanding bulk instert means inserting multiple rows, which i don't need.

I'm trying to use an array of object as a parameter for a query:

function saveDomicilio(id_establecimiento, token, order, total){
var order = [{"id":1,"quantity":2},{"id":"3","quantity":"4"}];

console.log("Order" + order);  // logs correctly my order

var new_Domicilio = {
  id_establecimiento: id_establecimiento,
  id_usuario: token,
  orden: order,
  total : total
};

pool.getConnection(function(err, connection) {

if(err) { 
  console.log(err); 
  return; 
}

// make the query

connection.query("INSERT INTO domicilio SET ?", [new_Domicilio], function(err, results) {  
  if(err) { 
    console.log(err); 
    return; 
  }

  console.log("New domicilio created");
  return;

}); // query
}); // pool
};

There seems to be a problem with using an array I get the error:

{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''{\\"id\\":1,\\"cantidad\\":2}', total = 300

How am i supposed to do it?

If you want to save it in one row then don't wrap in with []

try this

connection.query("INSERT INTO `domicilio` SET ?", new_Domicilio, function(err, results) {  
  if(err) { 
    console.log(err); 
    return; 
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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