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.
答案 0 :(得分:1)
在cnxDB.js
设置3个连接:
var connections = {
<dbname>: null,
<dbname>: null,
<dbname>: null
}
转到mssql并查看&#34;快速示例&#34;。它创建一个连接并将其保存在变量中。您希望为每个数据库执行3次,并将其保存在connections
下相应的数据库名称下。
然后,从cnxDB.js
导出的函数应该可以知道您希望它们使用哪个数据库。通过它的外观,您希望有一些指示在该请求的主体中需要使用什么数据库。您可以使用它来选择数据库。