【问题标题】:golang database/sql using pq使用 pq 的 golang 数据库/sql
【发布时间】:2016-11-15 18:29:09
【问题描述】:

我遇到了这个问题

 db, err := sql.Open("postgres", "user=xxx dbname=xxx connect_timeout=5 sslmode=disable")
 if err != nil {
    log.Fatal(err)
 }

我的本​​地主机上没有安装 postgres,所以 sql.Open 应该返回一些错误,但实际上直到我尝试准备查询并最后我得到一个连接被拒绝错误

stmt, err := c.DB.Prepare("SELECT id FROM services WHERE name = $1")
if err != nil {
    log.Fatal(err)
}

这是预期的行为吗?或者我错过了什么......

【问题讨论】:

标签: go pq


【解决方案1】:

根据this是的这是预期的行为。 Open() 不会直接打开与数据库的连接。 而是在第一次实际使用数据库时打开第一个连接。

Open may just validate its arguments without creating a connection 
to the database. 
To verify that the data source name is valid, call Ping.

使用Ping()检查连接是否有效。

【讨论】:

  • 感谢 sadil,我应该更加耐心地阅读文档!
猜你喜欢
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2022-09-30
  • 1970-01-01
  • 2016-06-21
  • 2014-01-24
  • 2022-07-26
相关资源
最近更新 更多