2 回答

TA贡献1909条经验 获得超7个赞
该database/sql
包没有提供一种通用的方法来超时调用database/sql.Open
. 但是,各个驱动程序通过 DSN (dataSourceName) 连接字符串提供此功能。
sql.Open("postgres", "user=user dbname=dbname connect_timeout=5")
https://github.com/go-sql-driver/mysql
sql.Open("mysql", "user:password@/dbname?timeout=5s")
https://github.com/denisenkom/go-mssqldb
sql.Open("sqlserver", "sqlserver://username:password@host/instance?dial+timeout=5")
ETC ...

TA贡献1872条经验 获得超3个赞
从 Go 1.8 开始,sql.DB抽象现在接受context.Context,可用于更快地超时连接。
func (c *Client) DoLookup(ctx context.Context, id int) (string, error) {
var name string
// create a child context with a timeout
newCtx, cancel := context.WithTimeout(ctx, time.Second)
// release resources used in `newCtx` if
// the DB operation finishes faster than the timeout
defer cancel()
row := c.db.QueryRowContext(newCtx, "SELECT name FROM items WHERE id = ?", id)
err := row.Scan(&name)
if err != nil {
return "", err
}
return name, nil
}
如果你的DoLookup函数还没有使用context.Context(它真的应该!)你可以通过调用来创建一个父函数context.TODO()。
- 2 回答
- 0 关注
- 252 浏览
添加回答
举报