9

I'm trying go connect to my postgres database using the jackc/pgx package and I'm following the provided example. The problem is that the code gets stuck at the connect call. I've tried printing something right after it and it doesn't print.

var dbURL string = fmt.Sprintf("postgresql://%s:%s@%s:%s/%s", user, password, host, port, dbname)

fmt.Println(dbURL)

conn, err := pgx.Connect(context.Background(), dbURL)
if err != nil {
    fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
    os.Exit(1)
}
defer conn.Close(context.Background())

var text string
err = conn.QueryRow(context.Background(), "select text from questions where id=$1", 1).Scan(&text)
if err != nil {
    fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
    os.Exit(1)
}

fmt.Println(text)

Output:

postgresql://postgres:[email protected]:52269/database_name

What am I doing wrong? I can connect to the db with pgAdmin 4 and I've connected to it before using the standard sql from go.

connectionString := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", user, password, dbname)
a.DB, err = sql.Open("postgres", connectionString)
6
  • It doesn't go past this as I said. It doesn't return anyting. After printing the output, it gets stuck there and I have to ctrl+c. I realized the port is wrong and that fixes it. Shouldn't it give an error instead of being stuck there instead? Commented Jun 24, 2020 at 20:18
  • Shouldn't it be just postgres://... instead of postgresql://...? Commented Jun 24, 2020 at 20:27
  • The sources I've seen say postgresql Commented Jun 24, 2020 at 20:50
  • @Myntekt as long as you've tried with postgres:// and you're seeing the same issue, fair enough. Commented Jun 24, 2020 at 20:59
  • @Myntekt note also that your dbURL has no sslmode setting, while the allegedly working connectionString does, so maybe that's your issue? Commented Jun 24, 2020 at 21:01

2 Answers 2

7

Documentation for pgx says both connection string and URL are allowed

https://pkg.go.dev/github.com/jackc/pgx/v4/[email protected]#ParseConfig

Example DSN

user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10

Example URL

postgres://jack:[email protected]:5432/mydb?sslmode=verify-ca&pool_max_conns=10

Sign up to request clarification or add additional context in comments.

Comments

0

in your pgAdmin example you leave out the host, in which case it defaults to local unix socket, not localhost or 127.0.0.1

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.