Reputation: 103
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
Reputation: 48485
In situations like these, it pays to go through the following checklist:
psql -U user -p 5432 -h localhost test
?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.psql
) If not, fix the query first before continuing.Upvotes: 5