当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。