dougu0824 2016-02-24 01:47
浏览 66
已采纳

GO打开本地postgres连接

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条回答 默认 最新

  • douju2012 2016-02-24 02:27
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?