Take a look at the documentation Escaping query values . Your alternatives are:
1. Use the methods mysql.escape()
, connection.escape()
or pool.escape()
var userId = 'some user provided value';
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function (error, results, fields) {
if (error) throw error;
// ...
});
2. Use the ?
character as placeholder
connection.query(
'SELECT * FROM users WHERE id = ?',
[userId],
function (error, results, fields) {
if (error) throw error;
// ...
});
In your case, you can do something like this
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query(
'INSERT INTO posts SET ?',
post,
function (error, results, fields) {
if (error) throw error;
// ...
});
console.log(query.sql); // INSERT INTO posts SET 'id' = 1, 'title' = 'Hello MySQL'