Skip to content
This repository was archived by the owner on May 24, 2023. It is now read-only.

Commit 4fa7c72

Browse files
committed
Update accessing.md
1 parent 2717301 commit 4fa7c72

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

accessing.md

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,16 +25,14 @@ These "connections" may be file handles, sockets, network connections, or other
2525

2626
To create a `sql.DB`, you use `sql.Open()`. This returns a `*sql.DB`:
2727

28-
```go
29-
func main() {
30-
db, err := sql.Open("mysql",
31-
"user:password@tcp(127.0.0.1:3306)/hello")
32-
if err != nil {
33-
log.Fatal(err)
28+
func main() {
29+
db, err := sql.Open("mysql",
30+
"user:password@tcp(127.0.0.1:3306)/hello")
31+
if err != nil {
32+
log.Fatal(err)
33+
}
34+
defer db.Close()
3435
}
35-
defer db.Close()
36-
}
37-
```
3836

3937
In the example shown, we're illustrating several things:
4038

@@ -45,12 +43,10 @@ In the example shown, we're illustrating several things:
4543

4644
Perhaps counter-intuitively, `sql.Open()` **does not establish any connections to the database**, nor does it validate driver connection parameters. Instead, it simply prepares the database abstraction for later use. The first actual connection to the underlying datastore will be established lazily, when it's needed for the first time. If you want to check right away that the database is available and accessible (for example, check that you can establish a network connection and log in), use `db.Ping()` to do that, and remember to check for errors:
4745

48-
```go
4946
err = db.Ping()
5047
if err != nil {
5148
// do something here
5249
}
53-
```
5450

5551
Although it's idiomatic to `Close()` the database when you're finished with it, **the `sql.DB` object is designed to be long-lived.** Don't `Open()` and `Close()` databases frequently. Instead, create **one** `sql.DB` object for each distinct datastore you need to access, and keep it until the program is done accessing that datastore. Pass it around as needed, or make it available somehow globally, but keep it open. And don't `Open()` and `Close()` from a short-lived function. Instead, pass the `sql.DB` into that short-lived function as an argument.
5652

0 commit comments

Comments
 (0)