Node.js SQL 操作

2021-06-01 10:03 更新

1.9.1 【必須】SQL 語句默認(rèn)使用預(yù)編譯并綁定變量

  • 應(yīng)使用預(yù)編譯綁定變量的形式編寫 sql 語句,保持查詢語句和數(shù)據(jù)相分離

  1. // bad:拼接 SQL 語句查詢,存在安全風(fēng)險(xiǎn)
  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:使用預(yù)編譯綁定變量構(gòu)造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. });

  • 對于表名、列名等無法進(jìn)行預(yù)編譯的場景,如:__user_input__ 拼接到比如 limit, order by, group by , from tablename語句中。請使用以下方法:

方案1:使用白名單校驗(yàn)表名/列名

  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__ 轉(zhuǎn)換為整數(shù)

  1. // good
  2. let { orderType } = req.body;
  3. // 強(qiáng)制轉(zhuǎn)換為整數(shù)
  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. });
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號