lib / pq

Pure Go Postgres driver for database/sql
https://pkg.go.dev/github.com/lib/pq
MIT License
8.98k stars 909 forks source link

What's the proper way to escape parameters in connection string. #986

Open arvenil opened 4 years ago

arvenil commented 4 years ago

What's the proper way to escape password and other parameters in connection string? Is there a function that can be used for that?

dsn := fmt.Sprintf(
    "host='%s' port='%s' user='%s' password='%s' dbname='%s' sslmode='%s'",
    d.Host,
    d.Port,
    d.User,
    d.Pass,
    d.Name,
    d.SSL,
)

return sql.Open("postgres", dsn)
svenwltr commented 2 years ago

pq also seem to understand database URLs. Therefore building one with the url package should escape everything properly.

    dbURI, err := url.Parse("postgres://localhost:5432/postgres?sslmode=disable")
    _ = err
    dbURI.User = url.UserPassword("postgres", "postgres")
    db, err := sql.Open("postgres", dbURI.String())
    _ = err