如何在 Node.js 中动态创建数据库连接?

2024-03-31

我在 Node.js 服务器中使用express.js 框架创建了 API。我的数据库是mysql。我能够创建与数据库的连接。下面是连接代码。

现在我想动态创建连接。我有 2 个数据库(数据库第一和数据库第二)。

var mysql=require('mysql');

var connection=mysql.createPool({
    host:'localhost',
    user:'root',
    password:'',
    database:'databaseFirst'
});

module.exports=connection;

1)用户将首先使用数据库登录。

2)成功登录后,他们将获得数据库名称,如databaseSecond。现在所有其他API将为该登录用户使用databaseSecond。

3) 每个 API 将发送数据库名称,以便他们可以识别该用户正在使用哪个数据库。

请帮助我。


你可以做类似的事情: 这里参考链接:1.stack https://stackoverflow.com/questions/45304238/how-can-i-use-two-database-connections-in-node-js-mysql 2.文件 https://www.npmjs.com/package/mysql#establishing-connections, 节点数据库连接 https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

    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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Node.js 中动态创建数据库连接? 的相关文章

随机推荐