[英]Dynamically choosing database/tables in pg-promise API
pg-promise API recommends an initial connection object like: pg-promise API 建议使用初始连接 object,例如:
var pgp = require('pg-promise')();
const mysqlcon = `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:5432/my_database}` //note that 'my_database' is hardcoded here
var db = pgp(mysqlcon);
module.exports = db;
then I use this object to query table_customers in my_database database:然后我使用这个 object 来查询my_database数据库中的table_customers :
var db = require('./models/postgres')
db.many('SELECT * from table_customers')
.then(function (data) {
console.log('DATA:', data)
})
.catch(function (error) {
console.log('ERROR:', error)
})
This works perfectly fine, but if I were to select another table from another database, how could I dynamically modify the connection object to change my_database to another_database ?这工作得很好,但如果我要 select 来自另一个数据库的另一个表,我怎么能动态修改连接 object 以将my_database更改为another_database ?
Connections in PostgreSql are database-bound, so you just use two database objects: PostgreSql 中的连接是数据库绑定的,因此您只需使用两个数据库对象:
const mySqlCon1 = `postgres://.../database1`;
const mySqlCon2 = `postgres://.../database2`;
export const db1 = pgp(mySqlCon1);
export const db2 = pgp(mySqlCon2);
create variable for dynamic change TABLE or DATABASE为动态更改 TABLE 或 DATABASE 创建变量
var db = require('./models/postgres')
db.many('SELECT * FROM ${YOUR_VAR}')
.then(function (data) {
console.log('DATA:', data)
})
.catch(function (error) {
console.log('ERROR:', error)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.