当前位置:Gxlcms > 数据库问题 > nodejs之连接mysql数据库

nodejs之连接mysql数据库

时间:2021-07-01 10:21:17 帮助过:24人阅读

一:demo

  

var mysql = require(‘mysql‘); var connection = mysql.createConnection({     host    : ‘192.168.0.2‘,     port    : ‘3307‘,     user    : ‘radar‘,     password: ‘radar‘,     database: ‘radar‘ }); connection.connect();
connection.query(‘select 1+1 as solution‘, function (error, results, fields){     if (error) throw error;     console.log(‘The solution is: ‘,results[0].solution); });

  

 

二: 封装

config.js文件

module.exports = {     host     : ‘192.168.0.2‘,     port     : ‘3307‘,     user     : ‘radar‘,     password : ‘radar‘,     database : ‘radar‘, }     db.js文件 var mysql = require(‘mysql‘); var dbConfig = require(‘./db/config‘);
module.exports = {     query : function(sql,param,callback){         //每次使用的时候要创建链接,数据操作完之后要关闭连接             var connection = mysql.createConnection(dbConfig);         connection.connect(function(err){             if(err){                 console.log(‘数据库链接失败‘);                 throw err;             }             //开始数据库操作             connection.query(sql, param, function(err,results,fields){                 if(err){                     console.log(‘数据库操作失败‘);                     throw err;                 }
                //将查询出来的结果返回给回调函数,这个时候就没有必要使用错误前置的思想了,因为我们在这个文件中已经为错误进行了处理,如果数据检索错误,直接会阻塞到这个文件中                 callback && callback(JSON.parse(JSON.stringify(results)), JSON.parse(JSON.stringify(fields)));
                //results作为数据操作后的结果,fields作为数据库连接的一些字段                 //停止连接数据库,必须要在查询数据库之后,不然一调用这个方法,就直接停止连接,数据操作就会失败                 connection.end(function(err){                     if(err){                         console.log(‘关闭数据库连接失败!‘);                         throw err;                     }                 })             })         })     } }   test.js var express = require(‘express‘); var router = express.Router(); var db = require(‘./db‘);//引入数据库封装模块

router.get(‘/‘,function(req,res,next) {     db.query(‘select * from device‘,[] ,function(results,fields){         console.log(results);
        res.render(‘index‘, { title: ‘Express11‘});     }) });
module.exports = router;
exports.hello = function(req, res) {
    res.send(‘The time is ‘ + new Date().toString());      };  

 

nodejs之连接mysql数据库

标签:log   nod   sel   pre   ice   result   mys   call   config   

人气教程排行