Node.js, MySQL (using
node-mysql library
connect)
I could have one argument 'aaa'
or two arguments 'aaa' and 'bbb'
.
UPDATE user SET email = 'aaa' WHERE uid = 'xxx';
UPDATE user SET email = 'aaa', password = 'bbb' WHERE uid = 'xxx';
How could I use one query to overcome above cases? Like below ...
var sql = "UPDATE user SET email = ?, password = ? WHERE uid = ?;"
dbclient.query(sql, [email, password, uid], function (err, results) {
...
});
If two arguments were defined
, variable sql
was :
sql = "UPDATE user SET email = 'test@mail.com', password = 'abcd' WHERE uid = 1;";
If someone argument was undefined
, variable sql
was :
sql = "UPDATE user SET email = 'test@mail.com', password = password WHERE uid = 1;";
Please read the documentation, especially the section escaping query values. node-mysql
supports some neat use of object serialization.
The following example should be what you want (it uses format, but so does query()
internally):
var mysql = require( 'mysql' );
var credfull = {
email: "a@exemple.com",
password: "secret"
},
crednopwd = {
email: "a@exemple.com"
},
whereclause = {
uid: "blabla"
};
console.log( mysql.format( 'UPDATE user SET ? WHERE ?', [credfull, whereclause]) );
// UPDATE user SET `email` = 'a@exemple.com', `password` = 'secret' WHERE `uid` = 'blabla'
console.log( mysql.format( 'UPDATE user SET ? WHERE ?', [crednopwd, whereclause]) );
// UPDATE user SET `email` = 'a@exemple.com' WHERE `uid` = 'blabla'
Hope this helps.