zoukankan      html  css  js  c++  java
  • Node.js连接Mysql,并把连接集成进Express中间件中

    引言

         在node.js连接mysql的过程,我们通常有两种连接方法,普通连接和连接池。 这两种方法较为常见,当我们使用express框架时还会选择使用中间express-myconnection,可以单独对mysql配置,也可以把connection集成到express中间件中。 最后送上一个node.js 连接各种主流数据库示例代码。

    前提条件

          1、安装mysql对应的驱动,npm install mysql

          2、安装第三方插件express-connection, npm install express-connection

    普通连接

    var 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

  • 相关阅读:
    Linux日志分析和管理
    Linux日志分析和管理
    Linux中的网络配置
    Linux中的网络配置
    安全之路 —— C++实现进程守护
    Linux内核升级、GRUB2引导故障处理与密码破解
    Linux内核升级、GRUB2引导故障处理与密码破解
    Linux启动流程和服务管理(init和systemd)
    Linux启动流程和服务管理(init和systemd)
    Linux下逻辑卷LVM的管理和RAID磁盘阵列
  • 原文地址:https://www.cnblogs.com/sword-successful/p/5234890.html
Copyright © 2011-2022 走看看