node如何预防sql注入

960
2021/2/5 18:40:08
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

node如何预防sql注入

node预防sql注入的方法:

1.使用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

2.使用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'

或者改写成:

var post = {userId: 1, name: 'test'};

var query = connection.query('SELECT * FROM users WHERE ?', post, function(err, results) {

// ...

});

console.log(query.sql); // SELECT * FROM users WHERE id = 1, name = 'test'

3. 使用escapeId()编码SQL查询标识符,例如:

var sorter = 'date';

var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);

connection.query(sql, function(err, results) {

// ...

});

4.使用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'

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: mybatis是如何防止SQL注入的