You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pg-promise API如何动态修改连接配置切换数据库、选择数据表

pg-promise动态切换数据库解决方案

原有实现直接导出固定连接my_database的实例,数据库名硬编码在初始化逻辑中,无法动态切换,可通过将固定实例导出改为工厂函数导出的方式实现需求:

1. 修改数据库配置文件./models/postgres.js

// pg-promise实例仅需初始化1次
var pgp = require('pg-promise')();

// 导出可接收数据库名参数的工厂函数,动态生成对应库的连接实例
module.exports = function getDbInstance(databaseName) {
  const connectionStr = `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:5432/${databaseName}`;
  return pgp(connectionStr);
}

2. 动态切换数据库调用示例

var getDbInstance = require('./models/postgres');

// 查询my_database中的table_customers表
const dbMy = getDbInstance('my_database');
dbMy.many('SELECT * from table_customers')
  .then(function (data) {
    console.log('DATA:', data)
  })
  .catch(function (error) {
    console.log('ERROR:', error)
  })

// 查询another_database中的目标表
const dbAnother = getDbInstance('another_database');
dbAnother.many('SELECT * from 你的目标表名')
  .then(function (data) {
    console.log('DATA:', data)
  })
  .catch(function (error) {
    console.log('ERROR:', error)
  })

可选优化:增加连接实例缓存

如果业务中会频繁切换固定几个数据库,可增加实例缓存避免重复创建连接,提升性能:

var pgp = require('pg-promise')();
// 存储已创建的数据库连接实例
const dbCache = {};

module.exports = function getDbInstance(databaseName) {
  if (dbCache[databaseName]) {
    return dbCache[databaseName];
  }
  const connectionStr = `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:5432/${databaseName}`;
  const db = pgp(connectionStr);
  dbCache[databaseName] = db;
  return db;
}

内容的提问来源于stack exchange,提问作者brainoverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:06:01