|
| 1 | +/* |
| 2 | + * Copyright 2024 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_simple_query_connection_read_api] |
| 20 | + |
| 21 | +import com.google.cloud.bigquery.BigQuery; |
| 22 | +import com.google.cloud.bigquery.BigQueryOptions; |
| 23 | +import com.google.cloud.bigquery.BigQueryResult; |
| 24 | +import com.google.cloud.bigquery.Connection; |
| 25 | +import com.google.cloud.bigquery.ConnectionSettings; |
| 26 | +import java.sql.ResultSet; |
| 27 | +import java.sql.SQLException; |
| 28 | + |
| 29 | +public class SimpleQueryConnectionReadApi { |
| 30 | + |
| 31 | + public static void main(String[] args) { |
| 32 | + String query = |
| 33 | + "SELECT corpus, count(*) as corpus_count " |
| 34 | + + "FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;"; |
| 35 | + simpleQueryConnectionReadApi(query); |
| 36 | + } |
| 37 | + |
| 38 | + public static void simpleQueryConnectionReadApi(String query) { |
| 39 | + |
| 40 | + try { |
| 41 | + // Initialize client and create a Connection session. |
| 42 | + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); |
| 43 | + ConnectionSettings connectionSettings = |
| 44 | + ConnectionSettings.newBuilder() |
| 45 | + .setRequestTimeout(10L) |
| 46 | + .setMaxResults(100L) |
| 47 | + .setUseQueryCache(true) |
| 48 | + .build(); |
| 49 | + Connection connection = bigquery.createConnection(connectionSettings); |
| 50 | + |
| 51 | + // Execute the query using the Connection session. |
| 52 | + BigQueryResult bigQueryResult = connection.executeSelect(query); |
| 53 | + ResultSet resultSet = bigQueryResult.getResultSet(); |
| 54 | + |
| 55 | + while (resultSet.next()) { |
| 56 | + System.out.print("corpus:" + resultSet.getString("corpus")); |
| 57 | + System.out.print(", count:" + resultSet.getLong("corpus_count")); |
| 58 | + System.out.println(); |
| 59 | + } |
| 60 | + System.out.println("Query ran successfully"); |
| 61 | + } catch (SQLException e) { |
| 62 | + System.out.println("Query did not run \n" + e.toString()); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | +// [END bigquery_simple_query_connection_read_api] |
0 commit comments