官术网_书友最值得收藏!

Connecting to an SQL database

The first thing we need do before connecting to an SQL-like database is identify the particular database that we will be interacting with and import a corresponding driver. In the following examples, we will be connecting to a Postgres database and will utilize the github.com/lib/pq database driver for database/sql. This driver can be loaded via an empty import (with a corresponding comment):

import (
"database/sql"
"fmt"
"log"
"os"

// pq is the library that allows us to connect
// to postgres with databases/sql.
_ "github.com/lib/pq"
)

Now let's assume that you have exported the Postgres connection string to an environmental variable PGURL. We can easily create an sql.DB value for our connection via the follow code:

// Get the postgres connection URL. I have it stored in
// an environmental variable.
pgURL := os.Getenv("PGURL")
if pgURL == "" {
log.Fatal("PGURL empty")
}

// Open a database value. Specify the postgres driver
// for databases/sql.
db, err := sql.Open("postgres", pgURL)
if err != nil {
log.Fatal(err)
}
defer db.Close()

Note that we need to defer the close method on this value. Also, note that creating this value does not mean that you have made a successful connection to the database. This is merely a value used by database/sql to connect to the database when triggered to do so by certain operations (such as a query).

To ensure that we can make a successful connection to the database, we can use the Ping method:

if err := db.Ping(); err != nil {
log.Fatal(err)
}
主站蜘蛛池模板: 武汉市| 广河县| 周至县| 涟源市| 家居| 西丰县| 漳州市| 齐齐哈尔市| 杭州市| 西峡县| 平潭县| 泗水县| 德格县| 甘德县| 昌吉市| 洱源县| 株洲县| 台州市| 阜阳市| 邳州市| 疏勒县| 微山县| 沙雅县| 光山县| 湟中县| 牙克石市| 琼结县| 黑龙江省| 二连浩特市| 宕昌县| 德州市| 甘洛县| 湟源县| 吉安市| 长武县| 承德市| 义乌市| 义马市| 靖西县| 江安县| 石景山区|