Skip to content

Instantly share code, notes, and snippets.

@pocari
Created September 6, 2021 12:50
Show Gist options
  • Save pocari/3373b953089b205ab013b7552daada36 to your computer and use it in GitHub Desktop.
Save pocari/3373b953089b205ab013b7552daada36 to your computer and use it in GitHub Desktop.
go-query-context-sample
package main
import (
"context"
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
ctx := context.Background()
db, err := sql.Open("mysql", "root@tcp(127.0.0.1:3306)/mysql")
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(ctx, time.Millisecond*6000)
defer cancel()
rows, err := db.QueryContext(ctx, "select sleep(5) as v")
if err != nil {
switch err {
case context.DeadlineExceeded:
fmt.Printf("deadline found: %+v\n", err)
default:
fmt.Printf("other error: %+v\n", err)
}
return
}
defer rows.Close()
for rows.Next() {
var v string
if err := rows.Scan(&v); err != nil {
panic(err)
}
fmt.Printf("%+v\n", v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment