Node中使用MySQL數據庫

一、在Navicat中創建庫
在這裏插入圖片描述

二、配置使用

文件目錄:
在這裏插入圖片描述

配置MySQL(setting.js):

module.exports={
    host:"localhost",
    port:"3306",
    user:"root",
    pwd:"12345678",
    base:"yian"
}

連接MySQL(connection.js):

var mysql=require("mysql");
var setting=require("./setting");
var connection;
var connectionmysql=function(){
    connection=mysql.createConnection({
        host:setting.host,
        port:setting.port,
        user:setting.user,
        password:setting.pwd,
        database:setting.base
    });
}
connectionmysql();  //初始化連接數據庫
// 不帶參
exports.select=function(str,callback){
    connectionmysql();  //重新連接數據庫
    connection.query(str,function(err,res){
        if(err) throw err;
        callback(res);
        connection.end();  //關閉服務器
    });
}   
// 帶參
exports.find=function(str,params,callback){
    connectionmysql();  //重新連接數據庫
    connection.query(str,params,function(err,res){
        if(err) throw err;
        callback(res);
        connection.end();  //關閉服務器
    });
}     
  1. 單組數據

SQL語句(sql.js):

module.exports={
    findTitle:"select * from nav"
}

在 router.js 使用MySQL:

var mysql=require("../MySQL/connection");
var sql=require("../MySQL/sql");
module.exports=function(app){
    app.get("/",function(req,res){
        mysql.select(sql.findTitle,function(result){
            console.log(result);
            res.render("index",{
                navres:result
            });
        });
    });
}

在相應位置引用:

<div class="col-lg-9 toplist">
    <ul class="list-inline text-center">
        <%for(var i=0;i<navres.length;i++){%>
            <%if(i==0){%>
                <li class="list-inline-item topdefaultcolor"><a href="#"><%=navres[i].title%></a></li>
            <%}else{%>
                <li class="list-inline-item"><a href="#"><%=navres[i].title%></a></li>
            <%}%>
        <%}%>
        <li class="text-right"><img class="searchbtn" src="image/icon/bg.png"/></li>
    </ul>
</div>
  1. 多組數據

SQL語句(sql.js):

module.exports={
    findTitle:"select * from nav",
    userInfo:"select * from user"
}

在 router.js 使用MySQL:

var mysql=require("../MySQL/connection");
var sql=require("../MySQL/sql");
module.exports=function(app){
    app.get("/",function(req,res){
        async function getData(){
            var res1=await new Promise(function(resolve){
                mysql.select(sql.findTitle,function(result){
                    resolve(result);
                });
            });
            var res2=await new Promise(function(resolve){
                mysql.select(sql.userInfo,function(result){
                    resolve(result);
                });
            });
            var allres={
                navres:JSON.parse(JSON.stringify(res1)),
                userres:JSON.parse(JSON.stringify(res2))
            }
            return allres;
        }
        getData().then(function(result){
        	console.log(result);
            res.render("index",result);
        });
    });
}

結果如圖:
在這裏插入圖片描述
在相應位置引用:

<div class="col-lg-3 carditem">
    <h2>我的名片</h2>
    <p>網名:<%=userres[0].nickname%></p>
    <p>職業:<%=userres[0].job%></p>
    <p>現居:<%=userres[0].address%></p>
    <p>Email:<%=userres[0].email%></p>
</div>
  1. 在不同的路由中使用相同的數據

sql.js:

module.exports={
    findTitle:"select * from nav",
    userInfo:"select * from user",
    updateTitle:"select id,title from blog order by time desc limit 4",
    randomMsg:"select id,title,logo from blog",
    clickRank:"select id,title from blog order by num desc limit 7",
    tabFirst:"select id,title,intro,logo from blog where type=1",
    tabSecond:"select id,title,intro,logo from blog where type=2",
    tabThird:"select id,title,intro,logo from blog where type=3",
    tabFourth:"select id,title,intro,logo from blog where type=4",
    ownBlog:"select blog.id,title,intro,logo,time,type.typeinfo from blog,type where blog.type=type.id order by time desc limit 6",
    recommendInfo:"select id,title,logo,recommend from blog where recommend=1 limit 8",
    typeInfo:"select id,typeinfo from type",
    detailBlog:"select blog.id,title,intro,desinfo,content,num,time,image,type.typeinfo from blog,type where blog.type=type.id and blog.id=?"
}

promise.js:

var mysql=require("../MySQL/connection");
var sql=require("../MySQL/sql");
module.exports={
    findTitle:function(){
        return new Promise(function(resolve){
            mysql.select(sql.findTitle,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        })
    },
    userInfo:function(){
        return new Promise(function(resolve){
            mysql.select(sql.userInfo,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        })
    },
    updateTitle:function(){
        return new Promise(function(resolve){
            mysql.select(sql.updateTitle,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    randomMsg:function(){
        return new Promise(function(resolve){
            mysql.select(sql.randomMsg,function(result){
                //隨機兩條數據信息
                result=JSON.parse(JSON.stringify(result));
                var index;
                var res=[];
                for(var i=0;i<2;i++){
                    var randomVal=Math.floor(Math.random()*result.length);
                    if(randomVal==index){
                        i--;
                        continue;
                    }
                    index=randomVal;  //記錄上一次
                    res.push(result[index]);
                }
                resolve(res);
            });
        });
    },
    clickRank:function(){
        return new Promise(function(resolve){
            mysql.select(sql.clickRank,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    tabFirst:function(){
        return new Promise(function(resolve){
            mysql.select(sql.tabFirst,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    tabSecond:function(){
        return new Promise(function(resolve){
            mysql.select(sql.tabSecond,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    tabThird:function(){
        return new Promise(function(resolve){
            mysql.select(sql.tabThird,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    tabFourth:function(){
        return new Promise(function(resolve){
            mysql.select(sql.tabFourth,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    ownBlog:function(){
        return new Promise(function(resolve){
            mysql.select(sql.ownBlog,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    recommendInfo:function(){
        return new Promise(function(resolve){
            mysql.select(sql.recommendInfo,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    typeInfo:function(){
        return new Promise(function(resolve){
            mysql.select(sql.typeInfo,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    },
    detailBlog:function(id){
        return new Promise(function(resolve){
            mysql.find(sql.detailBlog,id,function(result){
                resolve(JSON.parse(JSON.stringify(result)));
            });
        });
    }
}

router.js:

var promise=require("../MySQL/promise");
module.exports=function(app){
    app.get("/",function(req,res){
        async function getData(){
            var res1=await promise.findTitle();
            var res2=await promise.userInfo();
            var res3=await promise.updateTitle();
            var res4=await promise.randomMsg();
            var res5=await promise.clickRank();
            var res6=await promise.tabFirst();
            var res7=await promise.tabSecond();
            var res8=await promise.tabThird();
            var res9=await promise.tabFourth();
            var res10=await promise.ownBlog();
            var res11=await promise.recommendInfo();
            var res12=await promise.typeInfo();
            var allres={
                titleindex:0,
                navres:res1,
                userres:res2,
                uptitleres:res3,
                randomres:res4,
                rankres:res5,
                tabfirstres:res6,
                tabsecondres:res7,
                tabthirdres:res8,
                tabfourthres:res9,
                blogres:res10,
                recommendres:res11,
                typeres:res12
            }
            return allres;
        }
        getData().then(function(result){
            res.render("index",result);
        });
    });
    app.get("/diary",function(req,res){
        async function getData(){
            var res1=await promise.findTitle();
            var res5=await promise.clickRank();
            var res10=await promise.ownBlog();
            var res11=await promise.recommendInfo();
            var allres={
                titleindex:1,
                navres:res1,
                rankres:res5,
                blogres:res10,
                recommendres:res11,
            }
            return allres;
        }
        getData().then(function(result){
            res.render("diary",result);
        });
    });
    app.get("/detail",function(req,res){
        // 獲取路徑傳值
        var blogid=req.query.id;
        if(!blogid){
            return;
        }
        async function getData(){
            var res1=await promise.findTitle();
            var res4=await promise.randomMsg();
            var res13=await promise.detailBlog(blogid);
            var allres={
                titleindex:0,
                navres:res1,
                randomres:res4,
                detailres:res13
            }
            return allres;
        }
        getData().then(function(result){
            res.render("detail",result);
        });
    });
}
發佈了152 篇原創文章 · 獲贊 25 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章