在 Golang 中使用 database/sql
包实现 QueryRow
方法调用超时的合适方法是什么?关于这个主题已经有很多讨论,我想知道 golang 1.7 中是否有解决方案/最佳实践,而不是像这里描述的那样使用 context
包:
Ability to timeout when wating for the connection from the pool
此外,似乎 context support一直implemented recently .使用上下文使连接超时的合适方法是什么?
最佳答案
就 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
关于go - Golang中使用database/sql包调用QueryRow方法超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39889160/