从 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()。