lib/pq连接成功,但查询失败,连接出现问题。

huangapple go评论87阅读模式
英文:

lib/pq connects but query fails with bad connection

问题

我正在运行一个来自Digital Ocean的全新安装的Ubuntu 14.04。我通过调用sudo apt-get install postgresql postgresql-contrib来安装了Postgres。我通过调用go get github.com/lib/pq来安装了Postgres驱动程序。

我创建了一个名为foo的Ubuntu用户。然后,我使用createuser --interactive命令创建了一个名为foo的Postgres角色,只具有Create DB属性。接下来,我通过调用createdb foo创建了一个新的数据库。最后,我使用CREATE TABLE创建了一个新表。哦,我还在我的.bashrc文件中添加了export PGHOST=/var/run/postgresql

然后,我在/home/foo/go/src/dbtest.go路径下编写了以下文件。

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

func main() {
    connInfo := "username=foo dbname=foo host=/var/run/postgresql sslmode=disable"
    db, err := sql.Open("postgres", connInfo)
    if err != nil {
        log.Fatalln(err)
    }
    defer db.Close()

    rows, err := db.Query("SELECT * FROM bar")
    if err != nil {
        log.Fatalln(err) // 代码在这里失败。
    }
    defer rows.Close()

    fmt.Println(rows)
}

我遇到的问题是,调用sql.Open时没有返回错误,但是当我调用db.Query时,出现了driver: bad connection错误。我可以正常使用用户foo在Postgres解释器中执行查询,但是在Go中尝试查询时失败。我怀疑这可能是一个权限问题。

英文:

I'm running a fresh install of Ubuntu 14.04 from Digital Ocean. I've installed Postgres by calling sudo apt-get install postgresql postgresql-contrib. I installed the Postgres driver by calling go get github.com/lib/pq.

I made an Ubuntu user called foo. Then, I used createuser --interactive to create a Postgres role called foo with only the attribute Create DB. Next, I create a new database by calling createdb foo. Finally, I create a new table with CREATE TABLE. Oh, and I've added export PGHOST=/var/run/postgresql to my .bashrc file.

Then, I wrote the following file at /home/foo/go/src/dbtest.go.

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

func main() {
    connInfo := "username=foo dbname=foo host=/var/run/postgresql sslmode=disable"
    db, err := sql.Open("postgres", connInfo)
    if err != nil {
        log.Fatalln(err)
    }
    defer db.Close()

    rows, err := db.Query("SELECT * FROM bar")
    if err != nil {
        log.Fatalln(err) // Code fails here.
    }
    defer rows.Close()

    fmt.Println(rows)
}

The problem I'm having is that the call to sql.Open doesn't return an error, but when I call db.Query I get driver: bad connection. I can use the Postgres interpreter just fine as user foo, but when I try a query from Go it fails. I suspect this might be a permission issue.

答案1

得分: 0

连接字符串参数应该是 user=foo,而不是 username=foo

英文:

The connection string parameter should be user=foo, not username=foo.

答案2

得分: 0

我遇到了同样的错误,原因是在另一个流程中上下文被取消了。

英文:

I had same error, the reason was context was cancelled in another flow.

huangapple
  • 本文由 发表于 2014年9月3日 10:20:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/25635241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定