ctx,cancel:=context.WithCancel(context.Background())gofunc(){// 1秒待ってからキャンセルtime.Sleep(1*time.Second)cancel()}()rows,err:=db.QueryContext(ctx,"SELECT name FROM test where id = ?",id)iferr!=nil{log.Fatal(err)}
packagemainimport("database/sql""database/sql/driver""log""time""github.com/mattn/go-sqlite3""github.com/shogo82148/go-sql-proxy")funcmain(){sql.Register("sqlite3-proxy",proxy.NewProxyContext(&sqlite3.SQLiteDriver{},&proxy.HooksContext{PreExec:func(_context.Context,_*proxy.Stmt,_[]driver.NamedValue)(interface{},error){// The first return value(time.Now()) is passed to both `Hooks.Exec` and `Hook.ExecPost` callbacks.returntime.Now(),nil},PostExec:func(_context.Context,ctxinterface{},stmt*proxy.Stmt,args[]driver.NamedValue,_driver.Result,_error)error{// The `ctx` parameter is the return value supplied from the `Hooks.PreExec` method, and may be nil.log.Printf("Query: %s; args = %v (%s)\n",stmt.QueryString,args,time.Since(ctx.(time.Time)))returnnil},}))db,err:=sql.Open("sqlite3-proxy",":memory:")iferr!=nil{log.Fatalf("Open filed: %v",err)}deferdb.Close()_,err=db.Exec("CREATE TABLE t1 (id INTEGER PRIMARY KEY)",)iferr!=nil{log.Fatal(err)}}