0
0

はじめに

タイトルのとおり、sql.Openは必ずしも接続を確立しないようです。

Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping.

DeepL翻訳

Openは、データベースへの接続を作成せずに引数を検証するだけかもしれません。データ・ソース名が有効かどうかを確認するには、DB.Ping を呼び出します。

なので、DBの接続を確実にチェックしたいなら、Ping()を使います。

ヘルスチェックするときにも使えそう。

package main

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

	_ "github.com/go-sql-driver/mysql"
)

var (
	dbUser     = os.Getenv("DB_USER")
	dbPassword = os.Getenv("DB_PASSWORD")
	dbDatabase = os.Getenv("DB_NAME")
	dbConn     = fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?parseTime=true", dbUser, dbPassword, dbDatabase)
)

func main() {
	db, err := sql.Open("mysql", dbConn)
	if err != nil {
		fmt.Println("fail to connect DB")
		return
	}

	if err := db.Ping(); err != nil {
		fmt.Println("fail to ping DB")
		return
	}
}

参考図書

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0