Node.js连接Mysql

火热的夏天,突然想来个Nodejs加Mysql,练手不多解释。

1.安装Nodejs, 官网自行下载:https://nodejs.org/en/download/,双击运行没什么好说的了

Windows: https://nodejs.org/dist/v4.4.7/node-v4.4.7-x86.msi
Mac: https://nodejs.org/dist/v4.4.7/node-v4.4.7.pkg

 

2. 创建目录+安装Express+mysql

$> mkdir DemoLear
$> cd DemoLear
$> mkdir routes
$> npm install express
$> npm install mysql

 目录结构:

DemoLear

|-- routes

  |-- mysql_route.js

|-- sample1_mysql.js

 

3. 代码 sample1_mysql.js

var express = require('express');
var app = express();

// MiddleWare or usually around here
// To-dos

//API Router
var router = express.Router();
var index = require('./routes/mysql_route').router;
app.use('/', index);

//Start Server
var server = app.listen(3000, function(){
    console.log("Server start at 127.0.0.1 3000");
});

 

4.代码: mysql_route.js

var express = require('express');
var router = express.Router();

var mysql = require('mysql');
var connnectionPool = mysql.createPool({
    host    : 'localhost',
    user    : 'root',
    password: 'XXXXX',
    database: 'test'
});

router.get('/:table', function(req, res){
    //res.send('Welcome Nodejs and Mysql ');

    connnectionPool.getConnection(function(err, db){
        if(err){
            console.error('CONNECTION error: ', err);
            res.statusCode = 503;
            res.send({
                result : 'error',
                err :  err.code
            });
        }
        else{
            //query the database
            console.log("CONNECTION SUCCESSFUL!");
            //res.send("CONNECTION SUCCESSFUL!");

            db.query('select * from '+ req.params.table , function(err, rows, fields){
                if(err){
                    console.log("Query data ERROR!");
                }
                res.send({
                    result: 'success',
                    err: '',
                    fields: fields,
                    data: rows,
                    count : rows.length
                });
                db.release();
            });
        }
    });

});

module.exports.router = router;

 

5. Mysql,服务:locahost, 表:artical,用户:root,密码:XXXXX

 

6. 运行命令行:

$> node sample1_mysql.js

 

7. 访问:

http://localhost:3000/artical

表名作为Url传递(红色字)

 

8.效果:

 9.总结:开发效率还是挺快的。

 

posted @ 2016-08-07 16:54  Marksion  阅读(2196)  评论(0编辑  收藏  举报