|
| 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_destination_table] |
| 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.TableId; |
| 25 | + |
| 26 | +public class SaveQueryToTable { |
| 27 | + |
| 28 | + public static void runSaveQueryToTable() { |
| 29 | + // TODO(developer): Replace these variables before running the sample. |
| 30 | + String query = |
| 31 | + "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;"; |
| 32 | + String destinationTable = "MY_TABLE"; |
| 33 | + String destinationDataset = "MY_DATASET"; |
| 34 | + |
| 35 | + saveQueryToTable(destinationDataset, destinationTable, query); |
| 36 | + } |
| 37 | + |
| 38 | + public static void saveQueryToTable(String destinationDataset, |
| 39 | + String destinationTableId, String query) { |
| 40 | + try { |
| 41 | + // Initialize client that will be used to send requests. This client only needs to be created |
| 42 | + // once, and can be reused for multiple requests. |
| 43 | + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); |
| 44 | + |
| 45 | + // Identify the destination table |
| 46 | + TableId destinationTable = TableId.of(destinationDataset, destinationTableId); |
| 47 | + |
| 48 | + // Build the query job |
| 49 | + QueryJobConfiguration queryConfig = |
| 50 | + QueryJobConfiguration.newBuilder(query).setDestinationTable(destinationTable).build(); |
| 51 | + |
| 52 | + // Execute the query. |
| 53 | + bigquery.query(queryConfig); |
| 54 | + |
| 55 | + // The results are now saved in the destination table. |
| 56 | + |
| 57 | + System.out.println("Saved query ran successfully"); |
| 58 | + } catch (BigQueryException | InterruptedException e) { |
| 59 | + System.out.println("Saved query did not run \n" + e.toString()); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | +// [END bigquery_query_destination_table] |
0 commit comments