|
| 1 | +/* |
| 2 | + * Copyright 2020 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.bigquery; |
| 18 | + |
| 19 | +// [START bigquery_query_params_named] |
| 20 | +import com.google.cloud.bigquery.BigQuery; |
| 21 | +import com.google.cloud.bigquery.BigQueryException; |
| 22 | +import com.google.cloud.bigquery.BigQueryOptions; |
| 23 | +import com.google.cloud.bigquery.QueryJobConfiguration; |
| 24 | +import com.google.cloud.bigquery.QueryParameterValue; |
| 25 | +import com.google.cloud.bigquery.TableResult; |
| 26 | + |
| 27 | +public class QueryWithNamedParameters { |
| 28 | + |
| 29 | + public static void queryWithNamedParameters() { |
| 30 | + try { |
| 31 | + // Initialize client that will be used to send requests. This client only needs to be created |
| 32 | + // once, and can be reused for multiple requests. |
| 33 | + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); |
| 34 | + |
| 35 | + String corpus = "romeoandjuliet"; |
| 36 | + long minWordCount = 250; |
| 37 | + String query = |
| 38 | + "SELECT word, word_count\n" |
| 39 | + + "FROM `bigquery-public-data.samples.shakespeare`\n" |
| 40 | + + "WHERE corpus = @corpus\n" |
| 41 | + + "AND word_count >= @min_word_count\n" |
| 42 | + + "ORDER BY word_count DESC"; |
| 43 | + |
| 44 | + // Note: Standard SQL is required to use query parameters. |
| 45 | + QueryJobConfiguration queryConfig = |
| 46 | + QueryJobConfiguration.newBuilder(query) |
| 47 | + .addNamedParameter("corpus", QueryParameterValue.string(corpus)) |
| 48 | + .addNamedParameter("min_word_count", QueryParameterValue.int64(minWordCount)) |
| 49 | + .build(); |
| 50 | + |
| 51 | + TableResult results = bigquery.query(queryConfig); |
| 52 | + |
| 53 | + results |
| 54 | + .iterateAll() |
| 55 | + .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString()))); |
| 56 | + |
| 57 | + System.out.println("Query with named parameters performed successfully."); |
| 58 | + } catch (BigQueryException | InterruptedException e) { |
| 59 | + System.out.println("Query not performed \n" + e.toString()); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | +// [END bigquery_query_params_named] |
0 commit comments