diff --git a/query_test.go b/query_test.go index 59cf9355..f10078bf 100644 --- a/query_test.go +++ b/query_test.go @@ -1898,3 +1898,74 @@ func TestQueryWithQueryRewriter(t *testing.T) { require.NoError(t, rows.Err()) }) } + +// This example uses Query without using any helpers to read the results. Normally CollectRows, ForEachRow, or another +// helper function should be used. +func ExampleConn_Query() { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + conn, err := pgx.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) + if err != nil { + fmt.Printf("Unable to establish connection: %v", err) + return + } + + // Setup example schema and data. + _, err = conn.Exec(ctx, ` +create temporary table products ( + id int primary key generated by default as identity, + name varchar(100) not null, + price int not null +); + +insert into products (name, price) values + ('Cheeseburger', 10), + ('Double Cheeseburger', 14), + ('Fries', 5), + ('Soft Drink', 3); +`) + if err != nil { + fmt.Printf("Unable to setup example schema and data: %v", err) + return + } + + rows, err := conn.Query(ctx, "select name, price from products where price < $1 order by price desc", 12) + + // It is unnecessary to check err. If an error occurred it will be returned by rows.Err() later. But in rare + // cases it may be useful to detect the error as early as possible. + if err != nil { + fmt.Printf("Query error: %v", err) + return + } + + // Ensure rows is closed. It is safe to close rows multiple times. + defer rows.Close() + + // Iterate through the result set + for rows.Next() { + var name string + var price int32 + + err = rows.Scan(&name, &price) + if err != nil { + fmt.Printf("Scan error: %v", err) + return + } + + fmt.Printf("%s: $%d\n", name, price) + } + + // rows is closed automatically when rows.Next() returns false so it is not necessary to manually close rows. + + // The first error encountered by the original Query call, rows.Next or rows.Scan will be returned here. + if rows.Err() != nil { + fmt.Printf("rows error: %v", err) + return + } + + // Output: + // Cheeseburger: $10 + // Fries: $5 + // Soft Drink: $3 +}