3

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.

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

4 Comments

There can be number of database. so we can not use hardcoded database name.
Do you have predefined database name?
yes i have. this can be 100+ databases. but i have all database name.
Please check its help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.