Bran S
Bran S

Reputation: 103

GO open local postgres connection

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?

Upvotes: 0

Views: 1503

Answers (1)

Herman Schaaf
Herman Schaaf

Reputation: 48485

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.

Upvotes: 5

Related Questions