NodeJS连接MySQL数据库

在本地或服务器通过npm install mysql下载最新的版本

var options = {
    'host': 'localhost',
    'port': '3306',
    'database': 'db',
    'user': 'root',
    'password': '123',
    'charset': 'utf8',
    'connectionLimit': '5',
    'supportBigNumbers': true,
    'bigNumberStrings': true
};
var mysql = require('mysql');
var pool = mysql.createPool(options);
pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query( 'SELECT * FROM user', function(err, rows) {
      console.log(rows);
    // And done with the connection.
    connection.end();

    // Don't use the connection here, it has been returned to the pool.
  });
});

然后把以上代码保存成一个mysql-test.js文件,在控制台输入命令

node mysql-test.js即可执行看到结果。

node+mysql+express把怎么把数据返回到前台

app.get('/page',function(req,res){
    //若干你的代码
    pool.getConnection(function(err,connection){
        connection.query("select * from xxx",function(err,rows){
                 if(!err) {
                    res.render('your page',{
                        results:rows
                    });
                 }
            });
    })
})

想要取得Mysql的CURD的结果就需要使用到Async的插件来同步串行取得结果集,不然因为callback嵌套太多层取不到结果集的。

结果集返回到回调函数:

var rs;
function GetData (connection) {
    console.log(rs);
}
var async = require('async');
async.series([
    function (callback) {
        var values = ['Chad'];
            connection.query('INSERT INTO member SET nickname = ?', values,
                function(error, results) {
                    if(error) {
                      console.log("ClientReady Error: " + error.message);
                      return;
                    }
                    console.log('Inserted: ' + results.affectedRows + ' row.');
                    console.log('Id inserted: ' + results.insertId);
                    rs = results;
                    callback(null,1);
                }
        ); 
    }, function (callback) {
        GetData(connection);
        callback(null,1);
    }],
    function (err, results) {
        return;
    }
);

http://www.tuicool.com/articles/iYvYfeM

0 Comments

  1. yeezy boost 350

    2017年7月5日 下午2:59,

    There are some interesting closing dates in this article however I don抰 know if I see all of them heart to heart. There is some validity but I’ll take hold opinion until I look into it further. Good article , thanks and we want more! Added to FeedBurner as properly

Leave a comment