简体   繁体   中英

Update query in node.js

I have to update a row in the database and writing this

var o_voto_foto = {
    Profilo: profilo,
    Foto: data.id_foto_votata,
    punteggio: data.voto,
};

connection.query('UPDATE prof_voto_foto SET ? WHERE profilo_id = :Profilo AND foto_id = :Foto',o_voto_foto, function(error, rows) {
    if (error) {
        var err = "Error on UPDATE 'votoFotoFancybox': " + error;
        console.error(err);
        throw err;
    }
    connection.end();

    callback();

});

but I get a syntax error. however, if the query is done with this syntax

connection.query('UPDATE prof_voto_foto SET punteggio = '+data.voto+' WHERE profilo_id = '+profilo+' AND foto_id = '+data.id_foto_votata,function(error, rows) {

I use this external library https://github.com/felixge/node-mysql

Doing this will definitely work:

var o_voto_foto = {
    Profilo: profilo,
    Foto: data.id_foto_votata,
    punteggio: data.voto,
};

var params = [o_voto_foto.punteggio, o_voto_foto.Profilo, o_voto_foto.Foto ];

connection.query('UPDATE prof_voto_foto SET punteggio = ? WHERE profilo_id = ? AND foto_id = ? ', params, function(error, rows) {

Replacing the parameters in the query starting with a colon which match entries in the parameter object will only work if you register a Custom queryFormat. See the example below. You can't mix ? and parameters starting with a colon.

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

var params2 = {
punteggio : '',
profilo_id : '',
photo_id : ''
};

connection.query('UPDATE prof_voto_foto SET punteggio = :punteggio WHERE profilo_id = :profilo_id AND foto_id = :photo_id ', params2, function(error, rows) {

o_voto_foto is an object. The escape looks for an array. Try using [o_voto_foto]

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