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:
importstatements: imports thedatabase/sqlpackage and thegithub.com/lib/pqpackage, 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 extract the year from a PostgreSQL timestamp?
- How can I create a hierarchical query in PostgreSQL?
- How can I use PostgreSQL and ZFS snapshots together?
- How can I set a PostgreSQL interval to zero?
- How can I use PostgreSQL's "zero if null" feature?
- How can I integrate PostgreSQL with Yii2?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How can I monitor PostgreSQL performance using Zabbix?
- How do I use PostgreSQL's XMIN and XMAX features?
- How can I troubleshoot zero damaged pages in PostgreSQL?
See more codes...