所以,我在节点 8.11.1 / express 4.16.3 / pg 7.4.2 中使用pg 模块
我尝试将池用于我的前端(只是选择),示例有些令人困惑。
在连接时它只使用一个新池,然后它表明我必须做pool.end()
const pool = new Pool({
user: 'dbuser',
host: 'database.server.com',
database: 'mydb',
password: 'secretpassword',
port: 3211,
})
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
pool.end()
})
我这样写了我的代码,Error: Cannot use a pool after calling end on the pool
如果我做了几次相同的查询,它就会打印出来。所以不行pool.end()
在查询中,示例中没有断开连接 (?)
我终于让我的代码像pooling一样。它显示了pool.on('error', (err, client) => {
函数,然后client.release()
在池中使用,因为“pool.query 在内部直接委托给 client.query”我猜?
那么,在 pg 中使用 pool 的正确方法是什么,以及如何在每次查询或失败后断开连接?我想出了这个
const pool = new pg.Pool({
user: 'user',
host: 'localhost',
database: 'myProject',
password: 'secret',
port: 5432
});
pool.on('error', (err, client) => {
console.error('error on client', err, 'on client' , client);
process.exit(-1);
});
app.get('/', (req, res)=>{
pool.connect()
.then(client => {
return client.query('select name from table')
.then(resolved => {
client.release();
res.render('index',{'testData': resolved.rows});
})
.catch(e => { //return client.query
client.release();
res.render('index',{'errorData': e});
})
.catch(e => { //pool.connect()
client.release();
res.render('index',{'errorData': e});
})
})
});
我不知道这是否可以以任何方式缩短。比如,如果catch(e => { ////pool.connect()...
需要或者它被覆盖pool.on('error', (err, client) => {...
此外,如果它像
const pool = new pg.Pool({
user: 'user',
host: 'localhost',
database: 'myProject',
password: 'secret',
port: 5432
});
app.get('/', (req, res)=>{
pool.query('...')
.then(resolved => {
pool.end();// pool disconnect ???
res.render('index',{
'testData': resolved.rows
});
})
.catch(e => {
pool.end();// pool disconnect ???
res.render('index',{
'testData': e
});
})
});
但我不知道这是否正确,因为没有pool.connect
,没有从该连接返回的客户端,也没有断开池的功能(只是为了结束它,再次以 结束Error: Cannot use a pool after calling end on the pool
)。
请就正确的池使用和语法提出建议
谢谢