Please see the following code. This is a piece of code that simulates database operations with a loop inside.
In this loop, each database operation requires a timeout context of 2 seconds.
My question is that when the number of loops is very large, the 12th line will create a lot of contexts, and the 13th line will leave a lot of defer codes to be executed. Is this the proper way to use Context? Is there a better solution?
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
// Fetch data (maybe more than 8000 rows) from database
rows, err := db.QueryContext(ctx,"......") // Please ignore the specific SQL statement and args.
if err != nil {
// error handle
}
defer rows.Close()
// handle each row in this loop
for rows.Next() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) // Line 11
defer cancel() //Line 12
_, err := db.ExecContext(ctx, "......") // Please ignore the specific SQL statement and args.
if err != nil {
// error handle
}
//...
}