RT,把之前写的Nodejs请求Mysql的方法优化了一下,废话不多说直接上代码:
npm install mysql --save
新建文件mysql.js
/**
* Date: 2020/10/28
* Auth: LiHuYong
* Desc: 数据库连接封装
*/
const mysql = require('mysql');
let db = {};
let pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
port: '3306',
database: 'dataTable',
connectionLimit: 10,
timezone: "08:00",
multipleStatements: true // 开启同时执行多条SQL
});
db.query = function(params, callback){
if (!params.sql) {
console.log('SQL IS EMPTY');
params.res.send({code: -1, msg: "SQL IS EMPTY"});
return;
}
pool.getConnection(function(err, connection){
connection.query(params.sql, params.sqlParams, function(err, results){
if(err){
console.log('[QUERY ERROR] - ', err.message);
params.res.send({code: -1, msg: "服务异常"});
}else{
callback(results);
}
connection.release();
});
});
};
module.exports = db;
项目中使用
// 这里我用了Express Router,具体在用的时候看自己项目路由时如何配置的就行
const express = require("express");
const router = express.Router();
const db = require('../mysql'); // 引入封装的模块
router.get("/list", function (req, res) {
// 关键代码
db.query({
req: req,
res: res,
sql: "SELECT * FROM table",
sqlParams: []
}, function(result){
res.send({code: 0, result: result});
});
});
module.exports = router;
Wonderful, what a webpage it is! This website gives useful information to us, keep it up. Thomasine Shepard Fidellas
emmm~