如何在 MySQL 中更新具有不同参数的查询
How to UPDATE a query with different arguments in MySQL
环境
Node.js, MySQL (using node-mysql library
connect)
起初
我可以 one argument 'aaa'
或 two arguments 'aaa' and 'bbb'
。
UPDATE user SET email = 'aaa' WHERE uid = 'xxx';
UPDATE user SET email = 'aaa', password = 'bbb' WHERE uid = 'xxx';
我的问题
如何使用一个查询来克服上述情况?就像下面...
var sql = "UPDATE user SET email = ?, password = ? WHERE uid = ?;"
dbclient.query(sql, [email, password, uid], function (err, results) {
...
});
如果两个参数是 defined
,变量 sql
是:
sql = "UPDATE user SET email = 'test@mail.com', password = 'abcd' WHERE uid = 1;";
如果有人参数是 undefined
,变量 sql
是:
sql = "UPDATE user SET email = 'test@mail.com', password = password WHERE uid = 1;";
请阅读文档,尤其是 escaping query values 部分。 node-mysql
支持对象序列化的一些巧妙使用。
以下示例应该是您想要的(它使用格式,但 query()
内部也是):
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'
希望对您有所帮助。
环境
Node.js, MySQL (using
node-mysql library
connect)
起初
我可以 one argument 'aaa'
或 two arguments 'aaa' and 'bbb'
。
UPDATE user SET email = 'aaa' WHERE uid = 'xxx';
UPDATE user SET email = 'aaa', password = 'bbb' WHERE uid = 'xxx';
我的问题
如何使用一个查询来克服上述情况?就像下面...
var sql = "UPDATE user SET email = ?, password = ? WHERE uid = ?;"
dbclient.query(sql, [email, password, uid], function (err, results) {
...
});
如果两个参数是
defined
,变量sql
是:sql = "UPDATE user SET email = 'test@mail.com', password = 'abcd' WHERE uid = 1;";
如果有人参数是
undefined
,变量sql
是:sql = "UPDATE user SET email = 'test@mail.com', password = password WHERE uid = 1;";
请阅读文档,尤其是 escaping query values 部分。 node-mysql
支持对象序列化的一些巧妙使用。
以下示例应该是您想要的(它使用格式,但 query()
内部也是):
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'
希望对您有所帮助。