postgresqlHow can I connect a Golang application to a PostgreSQL database?
To connect a Golang application to a PostgreSQL database, you need to use the database/sql
package. This package provides a generic interface for interacting with databases.
The following example code shows how to connect to a PostgreSQL database:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=postgres password=postgres dbname=example_db sslmode=disable")
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
The code above will output the following:
Successfully connected!
The code above consists of the following parts:
import
statements: imports thedatabase/sql
package and thegithub.com/lib/pq
package, which is needed for connecting to PostgreSQL.sql.Open
: opens a connection to the PostgreSQL database.db.Ping
: tests the connection.fmt.Println
: prints a success message.
For more information, please see the following links:
More of Postgresql
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How can I use PostgreSQL and ZFS snapshots together?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I use PostgreSQL's "zero if null" feature?
- How can I retrieve data from PostgreSQL for yesterday's date?
- How can I set a PostgreSQL interval to zero?
- How can I integrate PostgreSQL with Yii2?
- How do I use PostgreSQL and ZFS together?
- How can Zalando use PostgreSQL to improve its software development?
- How can I use PostgreSQL with Zabbix?
See more codes...