2

Environment

Node.js, MySQL (using node-mysql library connect)

At first

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';

My problem

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) {
    ...
});
  1. If two arguments were defined, variable sql was :

    sql = "UPDATE user SET email = '[email protected]', password = 'abcd' WHERE uid = 1;";
    
  2. If someone argument was undefined, variable sql was :

    sql = "UPDATE user SET email = '[email protected]', password = password WHERE uid = 1;";
    

1 Answer 1

7

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: "[email protected]",
        password: "secret"
    },
    crednopwd = {
        email: "[email protected]"
    },
    whereclause = {
        uid: "blabla"
    };

console.log( mysql.format( 'UPDATE user SET ? WHERE ?', [credfull, whereclause]) );
// UPDATE user SET `email` = '[email protected]', `password` = 'secret' WHERE `uid` = 'blabla'

console.log( mysql.format( 'UPDATE user SET ? WHERE ?', [crednopwd, whereclause]) );
// UPDATE user SET `email` = '[email protected]' WHERE `uid` = 'blabla'

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much!! I read the part #Escaping query identifiers, no wonder no progress :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.