I have created API using express.js framework in Node.js server. My database is mysql. i am able to create connection with database. Below is code for connection.
Now i want to create connection dynamically. I have 2 database ( databaseFirst and databaseSecond).
var mysql=require('mysql');
var connection=mysql.createPool({
host:'localhost',
user:'root',
password:'',
database:'databaseFirst'
});
module.exports=connection;
1) User will login using databaseFirst.
2) After successfully login, they will get database name like as databaseSecond.Now all other APIs will use databaseSecond for that logged user.
3) Each API will send database name so they can identify that which database is using for that user.
Kindly help me.
You can do similar : Here refrence link : 1. stack 2. documents , nodeDBConnection
var connection;
function createConnectionDB (host,dbName,userName,password) {
connection[dbName] = mysql.createConnection({
host : host,
user : userName,
password : password,
database : dbName
});
connection[dbName].connect();
};
// In API when You getting DBName 'db1' you can use
createConnectionDB('localhost','db1','username','password')
connection['db1'].query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection['db1'].end();
////So API when You getting DBName ('db2') you can use
createConnectionDB('localhost','db2','username','password')
connection['db2'].query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection['db2'].end();
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.