2016-02-25 72 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] 
/* ... */