使用Golang中的database/sql包调用QueryRow方法时的超时问题

11
1个回答

6

从go 1.7开始,您将需要在以下级别上实现自己的功能:

  • 池级别(问题链接)
  • 查询级别,必须实现自己的
    Query(query string, args ...interface{}) (*Rows, error)
  • 数据库级别使用事务设置查询超时时间,例如在SQL Server中,可以使用EXEC sp_configure 'remote query timeout', 10。但这种设计需要更多的往返服务器的请求。

我建议至少切换到go 1.8,因为大多数数据库操作现在都有一个上下文替代方案,许多更改可以在此文档中找到:up

示例

package main

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

    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

func main() {
    db, err := sql.Open("sqlite3", "/tmp/gorm.db")
    if err != nil {
        log.Panic(err)
    }
    ctx := context.Background()
    ctx, cancel := context.WithTimeout(ctx, time.Microsecond*10)
    defer cancel()
    res := db.QueryRowContext(ctx, "select id from orders")
    id := -1
    if err := res.Scan(&id); err != nil {
        log.Panic(err)
    }
    log.Print(id)
}

输出:

2018/06/18 19:19:03 interrupted
panic: interrupted

goroutine 1 [running]:
log.Panic(0xc420053f48, 0x1, 0x1)
        /usr/local/Cellar/go/1.10.1/libexec/src/log/log.go:326 +0xc0
main.main()
        /tmp/main.go:23 +0x226
exit status 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接