github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/database/sql/example_cli_test.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package sql_test 6 7 import ( 8 "github.com/shogo82148/std/context" 9 "github.com/shogo82148/std/database/sql" 10 "github.com/shogo82148/std/flag" 11 "github.com/shogo82148/std/log" 12 "github.com/shogo82148/std/os" 13 "github.com/shogo82148/std/os/signal" 14 ) 15 16 func Example_openDBCLI() { 17 id := flag.Int64("id", 0, "person ID to find") 18 dsn := flag.String("dsn", os.Getenv("DSN"), "connection data source name") 19 flag.Parse() 20 21 if len(*dsn) == 0 { 22 log.Fatal("missing dsn flag") 23 } 24 if *id == 0 { 25 log.Fatal("missing person ID") 26 } 27 var err error 28 29 // ドライバを開く場合、通常、データベースへの接続は試みられません。 30 pool, err = sql.Open("driver-name", *dsn) 31 if err != nil { 32 33 // これは接続エラーではなく、DSN解析エラーや他の初期化エラーです。 34 log.Fatal("unable to use data source name", err) 35 } 36 defer pool.Close() 37 38 pool.SetConnMaxLifetime(0) 39 pool.SetMaxIdleConns(3) 40 pool.SetMaxOpenConns(3) 41 42 ctx, stop := context.WithCancel(context.Background()) 43 defer stop() 44 45 appSignal := make(chan os.Signal, 3) 46 signal.Notify(appSignal, os.Interrupt) 47 48 go func() { 49 <-appSignal 50 stop() 51 }() 52 53 Ping(ctx) 54 55 Query(ctx, *id) 56 }