使用Golang中的database / sql包调用QueryRow方法的超时
发布时间:2020-12-16 09:29:03 所属栏目:大数据 来源:网络整理
导读:使用Golang中的 database / sql包实现QueryRow方法调用超时的适当方法是什么?关于这个主题有很多讨论,我想知道golang 1.7中是否有解决方案/最佳实践,除了使用如下所述的上下文包: Ability to timeout when wating for the connection from the pool 此外,
使用Golang中的
database / sql包实现QueryRow方法调用超时的适当方法是什么?关于这个主题有很多讨论,我想知道golang 1.7中是否有解决方案/最佳实践,除了使用如下所述的上下文包:
Ability to timeout when wating for the connection from the pool 此外,似乎context support已经是implemented recently.使用上下文超时连接的适当方法是什么? 解决方法
至于1.7,您必须在以下级别实现自己的功能:
>池级别(问题链接) 我建议切换到至少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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |