- Machine Learning With Go
- Daniel Whitenack
- 257字
- 2021-07-08 10:37:28
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)
}
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- 高手是如何做產品設計的(全2冊)
- Vue.js 3.x從入門到精通(視頻教學版)
- PyQt從入門到精通
- NLTK基礎教程:用NLTK和Python庫構建機器學習應用
- Software Testing using Visual Studio 2012
- Expert Android Programming
- Flutter跨平臺開發入門與實戰
- Visual Basic程序設計上機實驗教程
- D3.js By Example
- C語言從入門到精通
- 匯編語言編程基礎:基于LoongArch
- Arduino可穿戴設備開發
- 微課學人工智能Python編程
- 零基礎學C語言(升級版)