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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM