當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO DB.PingContext用法及代碼示例

GO語言"database/sql"包中"DB.PingContext"類型的用法及代碼示例。

用法:

func(db *DB) PingContext(ctx context.Context) error

PingContext 驗證與數據庫的連接是否仍然存在,必要時建立連接。

例子:

package main

import (
	"context"
	"database/sql"
	"log"
	"time"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	// Ping and PingContext may be used to determine if communication with
	// the database server is still possible.
	//
	// When used in a command line application Ping may be used to establish
	// that further queries are possible; that the provided DSN is valid.
	//
	// When used in long running service Ping may be part of the health
	// checking system.

	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	status := "up"
	if err := db.PingContext(ctx); err != nil {
		status = "down"
	}
	log.Println(status)
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 DB.PingContext。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。