连接到Postgress DB

时间:2020-05-13 18:16:18

标签: node.js postgresql lambda

我正在编写一个lambda函数来连接到我在EC2实例上拥有的postgress数据库。我一直在使用“ pg”库进行连接,如他们在文档中所找到的那样,但是,我的函数不断跳过我方法的建立连接部分,只是继续执行并退出而未完成任何事情。

const client = new Client({
    user: 'user',
    host: 'xxxx.xxx.xxxx',
    database: 'dbname',
    password: 'password',
    port: 5432,
  })
  client.connect(err => {
    if (err) {
      console.error('connection error', err.stack)
    } else {
      console.log('connected')
    }
  })

  client.query('select count(*) from "Product"', (error, results) => {
    if (error) {
      console.log("Error when trying to query");
      throw error
    }
    console.log(results.rows)
  })

我正按照'pg'文档所说的方法(https://node-postgres.com/features/connecting)进行操作,但是无法弄清楚这里出了什么问题。我正在使用无服务器和nodejs12.x来实现此功能。

1 个答案:

答案 0 :(得分:0)

在查询之前,您不必等待建立连接。试试这个:

const client = new Client({
    user: 'user',
    host: 'xxxx.xxx.xxxx',
    database: 'dbname',
    password: 'password',
    port: 5432,
})
return client.connect(err => {
    if (err) {
        console.error('connection error', err.stack)
    } else {
        console.log('connected')
        return client.query('select count(*) from "Product"', (error, results) => {
            if (error) {
                console.log("Error when trying to query");
                throw error
            }
            console.log(results.rows)
        })

    }
})

尽管可以,但是创建一个promise链,因为这样可能更容易管理:

const client = new Client({
    user: 'user',
    host: 'xxxx.xxx.xxxx',
    database: 'dbname',
    password: 'password',
    port: 5432,
})
return client.connect().then(()=>{
    return client.query('select count(*) from "Product"')
}).then((results)=>{
    console.log(results.rows)
}).catch((err)=>{
    console.error('error', err.stack? err.stack : err)
})

我说,如果可以的话,请使用一个Promise链,因为我不确定pg库在连接和查询时返回什么。

希望这会有所帮助!