when to disconnect and when to end a pg client or pool

前端 未结 4 505
囚心锁ツ
囚心锁ツ 2021-02-01 02:38

My stack is node, express and the pg module. I really try to understand by the documentation and some outdated tutorials. I dont know when and how to disconnect and to e

4条回答
  •  青春惊慌失措
    2021-02-01 03:00

    The documentation over node-postgres's github says:

    pro tip: unless you need to run a transaction (which requires a single client for multiple queries) or you have some other edge case like streaming rows or using a cursor you should almost always just use pool.query. Its easy, it does the right thing ™️, and wont ever forget to return clients back to the pool after the query is done.

    So for non-transactional query, calling below code is enough.

    var pool = new Pool()
    
    pool.query('select username from user WHERE username= $1',[username], function(err, res) {
    
      console.log(res.rows[0].username)
    
    })

    By using pool.query, the library will take care of releasing the client after the query is done.

提交回复
热议问题