nodejs中如何防mySQL注入

如题,如能有具体示例或demo链接感激不尽

阅读 9.1k
1 个回答

使用escape()对传入参数进行编码

var userId = 1, name = 'test';
var query = connection.query('SELECT * FROM users WHERE id = ' + connection.escape(userId) + ', name = ' + connection.escape(name), function(err, results) {
    // ...
});
console.log(query.sql); // SELECT * FROM users WHERE id = 1, name = 'test'

使用connection.query()的查询参数占位符

var userId = 1, name = 'test';
var query = connection.query('SELECT * FROM users WHERE id = ?, name = ?', [userId, name], function(err, results) {
    // ...
});
console.log(query.sql); // SELECT * FROM users WHERE id = 1, name = 'test'

使用escapeId()编码SQL查询标识符

var sorter = 'date';
var sql    = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);
connection.query(sql, function(err, results) {
  // ...
});

使用mysql.format()转义参数

var userId = 1;
var sql = "SELECT * FROM ?? WHERE ?? = ?";
var inserts = ['users', 'id', userId];
sql = mysql.format(sql, inserts); // SELECT * FROM users WHERE id = 1

Ref: http://www.dengzhr.com/node-j...

PS: Google第一页就是答案

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏