|
| 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] |
| 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.TableResult; |
| 25 | + |
| 26 | +public class SimpleQuery { |
| 27 | + |
| 28 | + public static void runSimpleQuery() { |
| 29 | + // TODO(developer): Replace this query before running the sample. |
| 30 | + String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;"; |
| 31 | + simpleQuery(query); |
| 32 | + } |
| 33 | + |
| 34 | + public static void simpleQuery(String query) { |
| 35 | + try { |
| 36 | + // Initialize client that will be used to send requests. This client only needs to be created |
| 37 | + // once, and can be reused for multiple requests. |
| 38 | + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); |
| 39 | + |
| 40 | + // Create the query job. |
| 41 | + QueryJobConfiguration queryConfig = |
| 42 | + QueryJobConfiguration.newBuilder(query).build(); |
| 43 | + |
| 44 | + // Execute the query. |
| 45 | + TableResult result = bigquery.query(queryConfig); |
| 46 | + |
| 47 | + // Print the results. |
| 48 | + result.iterateAll().forEach(rows -> rows.forEach(row -> System.out.println(row.getValue()))); |
| 49 | + |
| 50 | + System.out.println("Query ran successfully"); |
| 51 | + } catch (BigQueryException | InterruptedException e) { |
| 52 | + System.out.println("Query did not run \n" + e.toString()); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | +// [END bigquery_query] |
0 commit comments