This example uses Query without using any helpers to read the results. Normally CollectRows, ForEachRow, or another helper function should be used.
()
| 2353 | // This example uses Query without using any helpers to read the results. Normally CollectRows, ForEachRow, or another |
| 2354 | // helper function should be used. |
| 2355 | func ExampleConn_Query() { |
| 2356 | ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) |
| 2357 | defer cancel() |
| 2358 | |
| 2359 | conn, err := pgx.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) |
| 2360 | if err != nil { |
| 2361 | fmt.Printf("Unable to establish connection: %v", err) |
| 2362 | return |
| 2363 | } |
| 2364 | |
| 2365 | if conn.PgConn().ParameterStatus("crdb_version") != "" { |
| 2366 | // Skip test / example when running on CockroachDB. Since an example can't be skipped fake success instead. |
| 2367 | fmt.Println(`Cheeseburger: $10 |
| 2368 | Fries: $5 |
| 2369 | Soft Drink: $3`) |
| 2370 | return |
| 2371 | } |
| 2372 | |
| 2373 | // Setup example schema and data. |
| 2374 | _, err = conn.Exec(ctx, ` |
| 2375 | create temporary table products ( |
| 2376 | id int primary key generated by default as identity, |
| 2377 | name varchar(100) not null, |
| 2378 | price int not null |
| 2379 | ); |
| 2380 | |
| 2381 | insert into products (name, price) values |
| 2382 | ('Cheeseburger', 10), |
| 2383 | ('Double Cheeseburger', 14), |
| 2384 | ('Fries', 5), |
| 2385 | ('Soft Drink', 3); |
| 2386 | `) |
| 2387 | if err != nil { |
| 2388 | fmt.Printf("Unable to setup example schema and data: %v", err) |
| 2389 | return |
| 2390 | } |
| 2391 | |
| 2392 | rows, err := conn.Query(ctx, "select name, price from products where price < $1 order by price desc", 12) |
| 2393 | // It is unnecessary to check err. If an error occurred it will be returned by rows.Err() later. But in rare |
| 2394 | // cases it may be useful to detect the error as early as possible. |
| 2395 | if err != nil { |
| 2396 | fmt.Printf("Query error: %v", err) |
| 2397 | return |
| 2398 | } |
| 2399 | |
| 2400 | // Ensure rows is closed. It is safe to close rows multiple times. |
| 2401 | defer rows.Close() |
| 2402 | |
| 2403 | // Iterate through the result set |
| 2404 | for rows.Next() { |
| 2405 | var name string |
| 2406 | var price int32 |
| 2407 | |
| 2408 | err = rows.Scan(&name, &price) |
| 2409 | if err != nil { |
| 2410 | fmt.Printf("Scan error: %v", err) |
| 2411 | return |
| 2412 | } |