2016-02-25 73 views
0

我想連接到服務器端的不同數據庫,因此我可以使用節點執行包含這兩個數據庫的查詢。節點訪問多個數據庫

我有一個config.js這樣的:

module.exports = { 
    database: { 
     user: 'brunojs', 
     password: 'bdpf5', 
     connectString: 'localhost:1521/orcl' 
    }, 
    jwtSecretKey: "[email protected]&QVA7x" 
}; 

這節省了我訪問的第一個數據庫的信息。

然後,我有一個list.js文件,執行查詢:

var oracledb = require('oracledb'); 
var jwt = require('jsonwebtoken'); 
var config = require(__dirname + '../../config.js'); 

function get(req, res, next) { 
    oracledb.getConnection(
     config.database, 
     function(err, connection){ 
      if (err) { 
       return next(err); 
      } 

      connection.execute(
       'select num_sequencial, notes, des_especialidade, dt_diag ' + 
       'from organite_repository ', 
       {},//no binds 
       { 
        outFormat: oracledb.OBJECT 
       }, 
       function(err, results){ 
        if (err) { 
         connection.release(function(err) { 
          if (err) { 
           console.error(err.message); 
          } 
         }); 

         return next(err); 
        } 

        res.status(200).json(results.rows); 

        connection.release(function(err) { 
         if (err) { 
          console.error(err.message); 
         } 
        }); 
       } 
      ); 
     } 
    ); 
} 

module.exports.get = get; 

,一切工作正常。

事情是,現在,我想要使用另一個數據庫執行查詢。我怎樣才能做到這一點?

回答

1

首先,添加第二個憑據對象在config.js

module.exports = { 
    database: { 
     user: 'brunojs', 
     password: 'bdpf5', 
     connectString: 'localhost:1521/orcl' 
    }, 
    database2: { 
     user: 'user2', 
     password: 'password', 
     connectString: 'someotherhost:1521/orcl' 
    }, 
    jwtSecretKey: "[email protected]&QVA7x" 
}; 

然後使用一個或其他位置:

oracledb.getConnection(
    config.database, // you could change this line to config.database2 
    function(err, connection){ 
     if (err) { ... 

如果您想查詢一個數據庫,然後另一個,你需要以保持對connection對象的引用(爲簡潔起見省略了錯誤檢查):

oracledb.GetConnection(
    config.database, 
    function(err, connection1) { 
     oracledb.GetConnection(
      config.database2, 
      function(err, connection2) { 
       // in this function you can use either connection object 
       connection1.execute(...); 
       connection2.execute(...); 
      } 
    }); 
+0

謝謝你這麼mych保羅。 如果我想使用這兩個數據庫執行查詢會怎麼樣? –

1

這稍微超出了你的問題的範圍,但你也可以看看Waterline。它支持設置多個數據庫,然後綁定模型,以便知道某些數據模型的存儲位置被抽象出來。

1

你總是可以使用在DB方聯繫,所以你的java代碼沒有連接到另一個數據庫,例如:

select num_sequencial, notes, des_especialidade, dt_diag 
from [email protected] 
UNION 
select num_sequencial, notes, des_especialidade, dt_diag 
from [email protected] 
/* ... */