Created
September 6, 2021 12:50
-
-
Save pocari/3373b953089b205ab013b7552daada36 to your computer and use it in GitHub Desktop.
go-query-context-sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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