打开本地PostgreSQL连接

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

GO open local postgres connection

问题

我的postgres在Mac上本地运行,端口号为5432。

它有一个名为test的数据库,在其中有一个名为test_table的表。

我正在尝试使用GO连接到它。

导入:

 "database/sql"
 _ "github.com/lib/pq"

主要代码:

db, err := sql.Open("postgres", "postgres://user:@localhost:5432/test")
if err != nil {
	log.Println(err)
}
defer db.Close()

if err2 := db.Ping(); err2 != nil {
 fmt.Println("无法保持连接")
}

db.QueryRow("INSERT INTO test.test_table (name) VALUES ('something') RETURNING id").Scan(&id)

fmt.Println(id)

为了测试连接,我运行了Ping,并尝试向test_table插入一行数据。但是返回给我:

无法保持连接
0

我该如何解决这个问题?

英文:

My postgres is running locally on Mac on a port 5432

It has database on it named test, and this database has one table in it called test_table

I'm trying to connect to it using GO.

Imports:

 "database/sql"
 _ "github.com/lib/pq"

Main:

db, err := sql.Open("postgres", "postgres://user:@localhost:5432/test")
if err != nil {
	log.Println(err)
}
defer db.Close()

if err2 := db.Ping(); err2 != nil {
 fmt.Println("Failed to keep connection alive")
}

db.QueryRow("INSERT INTO test.test_table (name) VALUES (`something`)) RETURNING id").Scan(&id)

fmt.Println(id)

To test the connection I'm running Ping and also try to Insert one line into test_table. But it returns me:

Failed to keep connection alive
0

How can I fix the problem?

答案1

得分: 5

在这种情况下,按照以下检查清单进行操作是值得的:

  • 你能使用与go服务器提供的相同参数连接到服务器吗?也就是说,你能运行 psql -U user -p 5432 -h localhost test 吗?
  • 你是否打印了所有的错误信息?在问题中,err2 应该被打印出来,因为它包含了关于发生了什么的关键信息。Scan 也会返回一个错误,但你没有将其保存到变量或打印出来。如果保存或打印了该错误,你可能会看到查询中的语法问题。
  • 你能在SQL shell(psql)中运行该查询吗?如果不能,请先修复查询,然后再继续。
英文:

In situations like these, it pays to go through the following checklist:

  • can you connect to the server using the same arguments provided to the go server? I.e. can you run psql -U user -p 5432 -h localhost test ?
  • are you printing all errors? In the question, err2 should be printed, as it contains critical information about what's going on. Scan also returns an error that is not being saved to a variable or printed. If it were, you might have seen the syntax problem in your query.
  • can you you run the query in the SQL shell? (psql) If not, fix the query first before continuing.

huangapple
  • 本文由 发表于 2016年2月24日 09:47:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/35591781.html
匿名

发表评论

匿名网友

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

确定