当前位置:Gxlcms > 数据库问题 > Node.js连接Mysql,并把连接集成进Express中间件中

Node.js连接Mysql,并把连接集成进Express中间件中

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

mysql = require(‘mysql‘); var connection = mysql.createConnection({ host : ‘localhost‘, user : ‘root‘, password : ‘secret‘, database : ‘my_db‘ }); connection.connect(); connection.query(‘select * from solution‘, function(err, rows, fields) { if (err) throw err; console.log(‘The solution is: ‘, rows); });

connection.end();
 

 

连接池

    引入连接池后,最省事之处就是你不用每次用完以后去手动关闭connection。连接池的option还有很多选项,可以根据自己的需要来配置。

var mysql = require(‘mysql‘);
var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : ‘example.org‘,
  user            : ‘bob‘,
  password    : ‘secret‘
});

pool.query(‘select  * from solution‘, function(err, rows, fields) {
  if (err) throw err;

  console.log(‘The solution is: ‘, rows);
});

    当然如果你的应用没有那么多,而你对连接池回收机制又不放心,也可以手动关闭连接实现把连接放回到资源池里,调用connection.release()

pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query( ‘SELECT something FROM sometable‘, function(err, rows) {
    // And done with the connection.
    connection.release();

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

    关闭整个连接池的连接

pool.end(function (err) {
  // all connections in the pool have ended
});

 

express-myconnection

       express-myconnection是一个Connect/Express自动提供mysql 连接的中间件。 共提供三中策略管理db连接。

  • single。 创建单数据库应用实例,连接从不会关闭,万一连接因故障断掉,它还会重新连接。
  • pool。   基于应用程序实例创建连接池,并且对每一个请求从连接池里提供连接,连接在每次response会自动释放返回到连接池里去。
  • request。 针对每个request创建新的连接, 并且在response结束时会自动关闭。

 

    这也是我在项目里所使用的方法,因为业务逻辑不复杂,没有封装db层,直接在app.js里配置,然后在路由层里直接调用。

 

app.js

var mysql = require(‘mysql‘), 
    myConnection = require(‘express-myconnection‘),
    dbOptions = {
      host: ‘localhost‘,
      user: ‘dbuser‘,
      password: ‘password‘,
      port: 3306,
      database: ‘mydb‘
    };
  
app.use(myConnection(mysql, dbOptions, ‘single‘); //作为中间件来使用

/router/order.js 在路由文件里应用

在这里也可以调用存储过程:conn.query(‘call usp_test‘,[传参数],function(err,result))

router.get(‘/cost‘, function(req, res, next) {
 
    req.getConnection(function(err, conn) {
        if (err) {
           
            return next(err);
        } else {
            conn.query(‘select * from test‘, [], function(err,result) {
                if (err) {
                    return next(err);
                } else {
                    res.Json(result); //可以直接把结果集转化Json返回给客户端
                }
            });
        }
    });

});

 

参考资料

   https://tonicdev.com/npm/express-myconnection

   http://expressjs.com/en/guide/database-integration.html

   https://www.terlici.com/2015/08/13/mysql-node-express.html

Node.js连接Mysql,并把连接集成进Express中间件中

标签:

人气教程排行