位置參數和指定類型

使用位置參數和指定參數類型執行查詢。

程式碼範例

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryParameterValue;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.TableResult;

// Sample to run query with positional types parameters.
public class QueryWithPositionalTypesParameters {

  public static void main(String[] args) {
    String[] words = {"and", "is", "the", "moon"};
    String corpus = "romeoandjuliet";
    Integer wordsCount = 250;
    String query =
        "SELECT word, word_count"
            + " FROM `bigquery-public-data.samples.shakespeare`"
            + " WHERE word IN UNNEST(?)"
            + " AND corpus = ?"
            + " AND word_count >= ?"
            + " ORDER BY word_count DESC";
    queryWithPositionalTypesParameters(query, words, corpus, wordsCount);
  }

  public static void queryWithPositionalTypesParameters(
      String query, String[] words, String corpus, Integer wordsCount) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      QueryParameterValue wordList = QueryParameterValue.array(words, StandardSQLTypeName.STRING);
      QueryParameterValue corpusParam = QueryParameterValue.of(corpus, StandardSQLTypeName.STRING);
      QueryParameterValue minWordCount =
          QueryParameterValue.of(wordsCount, StandardSQLTypeName.INT64);

      // Note: Standard SQL is required to use query parameters.
      QueryJobConfiguration queryConfig =
          QueryJobConfiguration.newBuilder(query)
              .addPositionalParameter(wordList)
              .addPositionalParameter(corpusParam)
              .addPositionalParameter(minWordCount)
              .build();

      TableResult results = bigquery.query(queryConfig);

      results
          .iterateAll()
          .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));

      System.out.println("Query with positional types parameters performed successfully.");
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Query not performed \n" + e.toString());
    }
  }
}

Rust

use google_cloud_bigquery::client::BigQuery;
use google_cloud_bigquery::model::{QueryParameter, QueryParameterType, QueryParameterValue};

pub async fn sample(project_id: &str) -> anyhow::Result<()> {
    let client = BigQuery::builder().build().await?;

    let mut rows = client
        .query("SELECT ? AS str_col, ? AS int_col, ? AS float_col;")
        .with_project_id(project_id)
        .set_parameter_mode("POSITIONAL")
        .set_query_parameters([
            QueryParameter::new()
                .set_parameter_type(QueryParameterType::new().set_type("STRING"))
                .set_parameter_value(QueryParameterValue::new().set_value("example string")),
            QueryParameter::new()
                .set_parameter_type(QueryParameterType::new().set_type("INT64"))
                .set_parameter_value(QueryParameterValue::new().set_value("42")),
            QueryParameter::new()
                .set_parameter_type(QueryParameterType::new().set_type("FLOAT64"))
                .set_parameter_value(QueryParameterValue::new().set_value("3.14159")),
        ])
        .set_location("US")
        .run()
        .await?
        .until_done()
        .await?
        .read();

    while let Some(row) = rows.next().await.transpose()? {
        let str_col: String = row.get("str_col");
        let int_col: i64 = row.get("int_col");
        let float_col: f64 = row.get("float_col");
        println!("String: {str_col}, Int: {int_col}, Float: {float_col}");
    }
    Ok(())
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具