连接池的数据库单次查询
1、下载:npm install promise-mysql
2、创建config文件夹下的mysqlpool.js文件,代码如下:
const mysql=require("promise-mysql");
//连接数据库
const pool=mysql.createPool({
host:"localhost",//ip地址
user:"root",//用户名
password:null,//密码
database:"mydate",//数据库名
connectionLimit:10
})
//公开pool对象
module.exports=pool
3.在userDao中执行sql语句
const pool=require("../config/mysqlpool")
module.exports={
//查询数据操作
selectUser(arr,fn){
return pool.getConnection().then(function (conn) {
conn.query("SELECT userName FROM t_user WHERE userName=? AND userPwd=?",arr).then(function (data) {
//返回查询的数据
fn(data)
}).catch(function (err) {
// 查询表发生的错误
})
}).catch(function (err) {
// 连接数据库发生的错误
})
}
}
4.在userCtrl中进行获得数据
const userDao=require("../dao/userDao");
//loginArr:输入的用户名和密码
userDao.selectUser(loginArr,function(data) {
if(data.length>0){
//登陆成功
req.session.data = userName//存入缓存
resp.render("",{userName:userName})//进入对应页面,传值
}else{
//登录失败
resp.render("")//留在当前页面
}
})
数据库多次查询
1、下载:npm install promise-mysql
2、创建config文件夹下的promisPool.js文件,代码如下:
const mysql= require("promise-mysql")
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydate',
connectionLimit: 10,
});
function getSqlConnection() {
return pool.getConnection().disposer(function(connection) {
pool.releaseConnection(connection);
});
}
module.exports = getSqlConnection;
3.在userCtrl中进行获得数据
const Promise = require("bluebird");
const getSqlConnection = require("../config/promisPool")
getData(req,resp){
Promise.using(getSqlConnection(), function(connection) {
return connection.query("SELECT count(*) as dataNum FROM t_student").then((data) => {
return data[0].dataNum
}).then((dataNum) => {
return connection.query("SELECT * FROM t_student limit 3").then((data) => {
resp.send({dataNum,data})
})
})
})
}