連接配接池的資料庫單次查詢
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})
})
})
})
}