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?

7
  • What does err2 contain? You should print that too. Commented Feb 24, 2016 at 1:58
  • it told "SSL is not enabled on the server", so I did sslmode=disable and now Ping goes through. The problem is, it still doesn't add a row into the table. How can I check the list of tables or something like this to make sure that I'm in a right database? Commented Feb 24, 2016 at 2:02
  • Shouldn't you be using Exec() for that? Commented Feb 24, 2016 at 2:04
  • QueryRow is correct (due to returning clause)... what error is Scan returning? Commented Feb 24, 2016 at 2:10
  • Scan is returning 0 and I don't see any rows added to the test_table Commented Feb 24, 2016 at 2:18

1 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.