英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论