简体   繁体   中英

How I can access multiple DB using ExpressJS?

I have a server with 3 databases with identical tables.

DB1, DB2 and DB3.

When I work with a database I use:

app.js

var cnxDB= require('./routes/cnxDB');
app.post('/userSave', cnxDB.userSave);

cnxDB.js:

var sql = require('mssql'); 
var qs = require('querystring');
var colors = require('colors');
var config = {user: 'user',password: 'pass',server: '127.0.0.1',database: nameDB',
    options: {
        encrypt: false
    }
};
sql.connect(config, function(err) {
   //Connection
});
exports.userSave = function(req, res) {
    //response
};

When initializing the application immediately makes the connection to the database.

I need to know how you can do to choose the database.

app.post('/selectBD', function(req, res){
  var body = req.body; // accede a la información enviada por el socket
  console.log(body);
  if(body.cnx == 1)
  {
    var cnx = require('./routes/bdUno');
    app.get('/yuri', cnx.findall);
  }
  if(body.cnx == 2)
  {
    var cnx = require('./routes/bdDos');
    app.get('/yuri', cnx.findall);
  }
  if(body.cnx == 3)
  {
    var cnx = require('./routes/bdTres');
    app.get('/yuri', cnx.findall);
  }

  res.status(200).json("Ok");
});

Thank you.

In cnxDB.js set up 3 connections:

var connections = {
    <dbname>: null,
    <dbname>: null,
    <dbname>: null
}

go to mssql and look at "Quick Example". It creates a connection and saves it in a variable. You'd want to do that 3 times for each db and save them in connections under the corresponding db name.

Then the functions you export from cnxDB.js should have a way to know which db you want them to use. By the looks of it you want to have some indication of what db needs to be used in the body of that request. You can use that to pick the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM