Node.js + Mysql 防止sql注入的写法

2024-01-09 18:27:55

关键代码

    const queryString = 'SELECT * FROM sys_user LIMIT ?, ?';
    let data =  await query(queryString, [startIndex,pageSize]); 

访问数据库相关代码

const mysql = require('mysql')

const pool = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
    password: '123456',
    database: 'lzwj_data',
    port: 3306
})


function camelCaseKeys(obj) {
    const result = {};
    for (let key in obj) {
        let newKey = key[0].toLowerCase() + key.slice(1).replace(/_([a-z])/g, function($0,$1){return $1.toUpperCase();});
        result[newKey] = obj[key];
    }
    return result;
}


let query = function( sql, values ) {
  // 返回一个 Promise
  return new Promise(( resolve, reject ) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        reject( err )
      } else {
        connection.query(sql, values, ( err, rows) => {
          if ( err ) {
            reject( err )
          } else {
            rows = rows.map(item => camelCaseKeys(item));
            resolve( rows )
          }
          // 结束会话
          connection.release()
        })
      }
    })
  })
}


module.exports =  query

一个分页查询人员信息的完整代码,查询语句实现了防止sql注入

router.get('/api/user/page', async (req, res) => {

    let pageNo = req.query.pageNo;
    let pageSize = sysUtils.strToInt(req.query.pageSize);
    const startIndex = sysUtils.strToInt((pageNo - 1) * pageSize);
    const queryString = 'SELECT * FROM sys_user LIMIT ?, ?';
    let data =  await query(queryString, [startIndex,pageSize]); 
    const countSql = 'select count(*) count from sys_user'
    let countData =  await query(countSql); 
    let count = sysUtils.strToInt(countData[0].count);

    let pageData = {
        total : count,   
        pages : sysUtils.pageCount(count,pageSize),
        records : data
    }

    res.send({
        status: 200,
        success : true,
        message: '',
        data: pageData,
    })
})

文章来源:https://blog.csdn.net/gdgztt/article/details/135404053
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。