将参数传递给 mysql 连接字符串

pass argument to mysql connection string

下面是我的代码(在文件 db.js 下)

function connection() {
  try {
    const mysql = require('mysql2');

    const pool = mysql.createPool({
      host: "mydb.abcd1234.ap-southeast-1.rds.amazonaws.com",
      database: "mydatabase",
      user: "user",
      password: "password", 
      connectionLimit: 11,
      waitForConnections: true,
      queueLimit: 0,
      namedPlaceholders: true
    });

    const promisePool = pool.promise();

    return promisePool;
  } catch (error) {
    return console.log(`Could not connect - ${error}`);
  }
}

const pool = connection();

module.exports = {
  connection: async () => pool.getConnection(),
  execute: (...params) => pool.execute(...params)
};

要使用它,我只需在需要它的文件顶部添加 var db = require('./../db.js');。此外,下面是我将如何执行任何 sql 语句

const myResult = await db.execute("Select COUNT(*) AS dataCount from teachers WHERE username = ?", [username]);

但现在我需要根据国家分离我的数据库。因此,我的数据库将以 mydatabase_ + 国家代码命名,例如 mydatabase_mymydatabase_jpmydatabase_uk 等。那么如何将国家代码传递给 function connection()

我试过

function connection(country) {
  try {
    const mysql = require('mysql2');

    const pool = mysql.createPool({
      host: "mydb.abcd1234.ap-southeast-1.rds.amazonaws.com",
      database: "mydatabase_" + country,
      user: "user",
      password: "password", 
      connectionLimit: 11,
      waitForConnections: true,
      queueLimit: 0,
      namedPlaceholders: true
    });

    const promisePool = pool.promise();

    return promisePool;
  } catch (error) {
    return console.log(`Could not connect - ${error}`);
  }
}

const pool = connection(country);

module.exports = {
  connection: async (country) => pool.getConnection(country),
  execute: (...params) => pool.execute(...params)
};

在调用页面,我做了

var db = require('./../db.js');
db.connection("my")

但对于上述内容,我会得到 ReferenceError: country is not defined,它指的是 const pool = connection(country);

行中的国家/地区

我是这样做的:

const mysql = require('mysql2');

const pool = function(country){
  var mydb = mysql.createPool({
    host: "mydb.abcd1234.ap-southeast-1.rds.amazonaws.com",
      database: "mydatabase_" + country,
      user: "user",
      password: "password", 
      connectionLimit: 11,
      waitForConnections: true,
      queueLimit: 0,
      namedPlaceholders: true
  });
  return mydb;
}

const promisePool = function(country){
  return pool(country).promise();
}

module.exports = {
  connection: async (country) => promisePool(country).getConnection(),
  execute: (country,...params) => promisePool(country).execute(...params)
};

并且在使用mysql的页面中会有这样的内容:

db.connection(country)
const myResult = await db.execute(country, "Select * from schools");