Node.js SQL 操作

2021-06-01 10:03 更新

1.9.1 【必须】SQL 语句默认使用预编译并绑定变量

  • 应使用预编译绑定变量的形式编写 sql 语句,保持查询语句和数据相分离

  1. // bad:拼接 SQL 语句查询,存在安全风险
  2. const mysql = require("mysql");
  3. const connection = mysql.createConnection(options);
  4. connection.connect();
  5. const sql = util.format("SELECT * from some_table WHERE Id = %s and Name = %s", req.body.id, req.body.name);
  6. connection.query(sql, (err, result) => {
  7. // handle err..
  8. });
  9. // good:使用预编译绑定变量构造SQL语句
  10. const mysql = require("mysql");
  11. const connection = mysql.createConnection(options);
  12. connection.connect();
  13. const sql = "SELECT * from some_table WHERE Id = ? and Name = ?";
  14. const sqlParams = [req.body.id, req.body.name];
  15. connection.query(sql, sqlParams, (err, result) => {
  16. // handle err..
  17. });

  • 对于表名、列名等无法进行预编译的场景,如:__user_input__ 拼接到比如 limit, order by, group by , from tablename语句中。请使用以下方法:

方案1:使用白名单校验表名/列名

  1. // good
  2. const tableSuffix = req.body.type;
  3. if (["expected1", "expected2"].indexOf(tableSuffix) < 0) {
  4. // 不在表名白名单中,拒绝请求
  5. return ;
  6. }
  7. const sql = `SELECT * from t_business_${tableSuffix}`;
  8. connection.query(sql, (err, result) => {
  9. // handle err..
  10. });

方案2:使用反引号包裹表名/列名,并过滤 __user_input__ 中的反引号

  1. // good
  2. let { orderType } = req.body;
  3. // 过滤掉__user_input__中的反引号
  4. orderType = orderType.replace("`", "");
  5. const sql = util.format("SELECT * from t_business_feeds order by `%s`", orderType);
  6. connection.query(sql, (err, result) => {
  7. // handle err..
  8. });

方案3:将 __user_input__ 转换为整数

  1. // good
  2. let { orderType } = req.body;
  3. // 强制转换为整数
  4. orderType = parseInt(orderType, 10);
  5. const sql = `SELECT * from t_business_feeds order by ${orderType}`;
  6. connection.query(sql, (err, result) => {
  7. // handle err..
  8. });
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号