Node-mysql insert query with two values?

限于喜欢 提交于 2019-12-23 17:59:00

问题


This is my current javascript.

var connection = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: 'root',
   database: 'codify',
   port:     '8889'     
})


connection.connect();
 //var querydata = +"'"+data.RegUsername + "','"+data.RegPassword+"'" 
  connection.query("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES ?", data.RegUsername,+","+ data.Regpassword , function(err,rows,fields){
   if (err) throw err;
    })
  });*/

This query causes an error, what am I doing wrong?


回答1:


What you're doing wrong is that you're trying to concatenate your two values into a single string and have that string substituted into your single ?. If you're using a single ?, you need to pass in an object where the object's parameters are the same as the database field names.

I'd do it like this:

let payload = {
    UsernameDB: data.RegUsername,
    PasswordDB: data.Regpassword
};

connection.query("INSERT INTO Codify SET ?", payload, function(err, rows) {

});

You can also do it like this with an array instead of an object:

let sql = "INSERT INTO Codify (UsernameDB, PasswordDB) VALUES (?, ?)";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {

});

or like this:

let sql = "INSERT INTO Codify SET UsernameDB = ?, PasswordDB = ?";
connection.query(sql, [ data.RegUsername, data.Regpassword ],  function(err, rows) {

});

But I find using a single ? along with an object is more readable.




回答2:


placeholder ( ? character) will escape your querydata for avoid sql-injection. cause you don't use combined string for query. use placeholders to each inserted value. like

("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES (?,?)", [data.RegUsername,data.Regpassword] , function () )

check nodejs mysql driver document here



来源:https://stackoverflow.com/questions/40350747/node-mysql-insert-query-with-two-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!