

 Amazon Redshift 將不再支援從修補程式 198 開始建立新的 Python UDFs。現有 Python UDF 將繼續正常運作至 2026 年 6 月 30 日。如需詳細資訊，請參閱[部落格文章](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Amazon Redshift 資料 API
<a name="data-api"></a>

Amazon Redshift 資料 API 可簡化存取 Amazon Redshift 資料倉儲的過程，讓您不需管理資料庫驅動器、連線、網路組態、資料緩衝、憑證等。您可以使用資料 API 操作搭配 AWS SDK 來執行 SQL 陳述式。如需資料 API 操作的詳細資訊，請參閱 [Amazon Redshift 資料 API 參考](https://docs.aws.amazon.com/redshift-data/latest/APIReference/)。

資料 API 不需要與資料庫持續連線。而是提供安全的 HTTP 端點並與 AWS SDKs整合。您可以使用端點來執行 SQL 陳述式，而不需管理連線。對資料 API 的呼叫是非同步的。資料 API 可以使用存放在 中的登入資料 AWS Secrets Manager 或臨時資料庫登入資料。不管是哪一種授權方法，都不需要在 API 呼叫中傳遞密碼。如需詳細資訊 AWS Secrets Manager，請參閱*AWS Secrets Manager 《 使用者指南*》中的[什麼是 AWS Secrets Manager？](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)。您也可以使用 AWS IAM Identity Center 進行授權。

使用資料 API，您可以使用 Web 服務型應用程式以程式設計方式存取 Amazon Redshift 資料 AWS Lambda，包括 Amazon SageMaker AI 筆記本和 AWS Cloud9。如需這些應用程式的詳細資訊，請參閱 [AWS Lambda](https://aws.amazon.com/lambda/)、[Amazon SageMaker AI](https://aws.amazon.com/sagemaker/) 和 [AWS Cloud9](https://aws.amazon.com/cloud9/)。

若要進一步了解資料 API，請參閱 *AWS 巨量資料部落格*中的[開始使用 Amazon Redshift 資料 API](https://aws.amazon.com/blogs/big-data/get-started-with-the-amazon-redshift-data-api/)。

## 使用 Amazon Redshift 資料 API
<a name="data-api-workflow"></a>

在使用 Amazon Redshift 資料 API 之前，請先檢閱下列步驟：

1. 確定身為資料 API 呼叫者的您是否已獲得授權。如需授權的相關資訊，請參閱 [授權 Amazon Redshift 資料 API 的存取](data-api-access.md)。

1. 確定您打算使用來自 Secrets Manager 的身分驗證憑證、暫時憑證或是使用 AWS IAM Identity Center來呼叫資料 API。如需詳細資訊，請參閱[在呼叫 Amazon Redshift 資料 API 時選擇資料庫身分驗證憑證](#data-api-calling-considerations-authentication)。

1. 如果您使用 Secrets Manager 來取得驗證憑證，請設定機密。如需詳細資訊，請參閱[在 中存放資料庫登入資料 AWS Secrets Manager](data-api-secrets.md)。

1. 在呼叫資料 API 時，檢閱考量和限制。如需詳細資訊，請參閱[呼叫 Amazon Redshift 資料 API 時的考量](#data-api-calling-considerations)。

1. 從 AWS Command Line Interface (AWS CLI)、從您自己的程式碼呼叫資料 API，或使用 Amazon Redshift 主控台中的查詢編輯器。如需從 AWS CLI進行呼叫的範例，請參閱[呼叫資料 API](data-api-calling.md)。

## 呼叫 Amazon Redshift 資料 API 時的考量
<a name="data-api-calling-considerations"></a>

在呼叫資料 API 時，請考量下列事項：
+ Amazon Redshift 資料 API 可以存取 Amazon Redshift 所佈建的叢集和 Redshift Serverless 工作群組中的資料庫。如需 Redshift Data API 可用 AWS 區域 位置的清單，請參閱 中針對 [Redshift Data API](https://docs.aws.amazon.com/general/latest/gr/redshift-service.html) 列出的端點*Amazon Web Services 一般參考*。
+ 查詢的持續時間上限為 24 小時。
+ 每個 Amazon Redshift 叢集的作用中查詢 (`STARTED` 和 `SUBMITTED`查詢） 數目上限為 500。
+ 查詢結果大小上限為 500 MB (gzip 壓縮後)。如果呼叫傳回超過 500 MB 的回應資料，則呼叫會結束。
+ 查詢結果的保留時間上限為 24 小時。
+ 查詢陳述式的大小上限為 100 KB。
+ 資料 API 可用於查詢以下節點類型的單節點和多節點叢集：
  + dc2.large
  + dc2.8xlarge
  + ra3.large
  + ra3.xlplus
  + ra3.4xlarge
  + ra3.16xlarge
+ 叢集必須位於以 Amazon VPC 服務為基礎的虛擬私有雲端 (VPC) 中。
+ 根據預設，若使用者的 IAM 角色與 `ExecuteStatement` 或 `BatchExecuteStatement` API 操作的執行者相同，則使用者可以使用 `CancelStatement`、`DescribeStatement`、`GetStatementResult`、`GetStatementResultV2` 和 `ListStatements` API 操作來處理相同的陳述式。若要處理其他使用者的相同 SQL 陳述式，使用者必須能夠擔任執行了 SQL 陳述式之使用者的 IAM 角色。如需擔任角色的相關資訊，請參閱 [授權 Amazon Redshift 資料 API 的存取](data-api-access.md)。
+ 在 `BatchExecuteStatement` API 操作的 `Sqls` 參數中，SQL 陳述式會以單一交易的形式來執行。其會依陣列順序循序執行。後續的 SQL 陳述式要等到陣列中的前一個陳述式完成後才會啟動。如果有任何 SQL 陳述式失敗，由於其以單一交易的形式執行，因此所有工作都會復原。
+ `ExecuteStatement` 或 `BatchExecuteStatement` API 操作中所使用的用戶端字符保留時間上限為 8 小時。
+ 如果 Amazon Redshift 佈建叢集和 Redshift Serverless 工作群組是使用客戶受管金鑰加密，則 Redshift 會建立授權，允許 Redshift Data API 將金鑰用於其操作。如需詳細資訊，請參閱 [AWS KMS 搭配 Amazon Redshift 資料 API 使用](data-api-kms.md)。
+ 在限流請求之前，Redshift Data API 中的每個 API 都有每秒交易配額。如需配額的相關資訊，請參閱 [Amazon Redshift Data API 的配額](amazon-redshift-limits.md#data-api-quotas-account)。如果請求的速率超過配額，則傳回附帶 HTTP 狀態碼：400 的 `ThrottlingException`。若要回應限流，請使用重試策略，如 *AWS SDK 和工具參考指南*中的[重試行為](https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html)中所述。針對某些 AWS SDK 中的限流錯誤，這個策略會自動實作。
**注意**  
在 中 AWS Step Functions，預設不會啟用重試。如果您需要在 Step Functions 狀態機器中呼叫 Redshift Data API，請在 Redshift Data API 呼叫中包含 `ClientToken` 等冪性參數。`ClientToken` 的值需要在重試之間持續存在。在 `ExecuteStatement` API 請求的下列範例片段中，表達式 `States.ArrayGetItem(States.StringSplit($$.Execution.Id, ':'), 7)` 會使用內部函數來擷取 `$$.Execution.Id` 的 UUID 部分，這對於狀態機器的每次執行而言都是唯一的。如需詳細資訊，請參閱 *AWS Step Functions 開發人員指南*中的[內部函數](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html)。  

  ```
  {
    "Database": "dev",
    "Sql": "select 1;",
    "ClusterIdentifier": "MyCluster",
    "ClientToken.$": "States.ArrayGetItem(States.StringSplit($$.Execution.Id, ':'), 7)"
  }
  ```

## 在呼叫 Amazon Redshift 資料 API 時選擇資料庫身分驗證憑證
<a name="data-api-calling-considerations-authentication"></a>

當您呼叫資料 API 時，您會對部分 API 操作使用下列其中一種身分驗證方法。每種方法都需要不同的參數組合。

**AWS IAM Identity Center**  
資料 API 可透過 AWS IAM Identity Center中註冊的單一登入使用者存取。如需有關設定 IAM Identity Center 的步驟資訊，請參閱 [使用資料 API 搭配可信身分傳播](data-api-trusted-identity-propagation.md)。

**AWS Secrets Manager**  
使用此方法，提供存放在 AWS Secrets Manager 中具有 `username`和 `secret-arn`之秘密的 `password`。指定的機密包含用來連線至所指定 `database` 的憑證。當您連線至叢集時，您也會提供資料庫名稱，如果您提供叢集識別碼 (`dbClusterIdentifier`)，則其必須符合儲存在機密中的叢集識別碼。當您連線至無伺服器工作群組時，您也會提供資料庫名稱。如需詳細資訊，請參閱[在 中存放資料庫登入資料 AWS Secrets Manager](data-api-secrets.md)。  
透過此方法，您也可以提供指定資料所在 AWS 區域 位置`region`的值。

**臨時憑證**  
使用此方法時，請選擇下列其中一個選項：  
+ 在連線至無伺服器工作群組時，請指定工作群組名稱和資料庫名稱。資料庫的使用者名稱會衍生自 IAM 身分。例如，`arn:iam::123456789012:user:foo` 的資料庫使用者名稱為 `IAM:foo`。此外，也需要用來呼叫 `redshift-serverless:GetCredentials` 操作的許可。
+ 以 IAM 身分連線至叢集時，請指定叢集識別碼和資料庫名稱。資料庫的使用者名稱會衍生自 IAM 身分。例如，`arn:iam::123456789012:user:foo` 的資料庫使用者名稱為 `IAM:foo`。此外，也需要用來呼叫 `redshift:GetClusterCredentialsWithIAM` 操作的許可。
+ 以資料庫使用者身分連線至叢集時，請指定叢集識別碼、資料庫名稱和資料庫使用者名稱。此外，也需要用來呼叫 `redshift:GetClusterCredentials` 操作的許可。如需有關在使用此方法進行連線時要如何加入資料庫群組的資訊，請參閱[連線到叢集時加入資料庫群組](data-api-dbgroups.md)。
透過此方法，您也可以提供指定資料所在 AWS 區域 位置`region`的值。

## 在呼叫 Amazon Redshift 資料 API 時映射 JDBC 資料類型
<a name="data-api-calling-considerations-jdbc"></a>

 下表會將 Java Database Connectivity (JDBC) 資料類型對應至您在資料 API 呼叫中指定的資料類型。


****  

|  JDBC 資料類型  |  資料 API 資料類型  | 
| --- | --- | 
|  `INTEGER, SMALLINT, BIGINT`  |  `LONG`  | 
|  `FLOAT, REAL, DOUBLE`  |  `DOUBLE`  | 
|  `DECIMAL`  |  `STRING`  | 
|  `BOOLEAN, BIT`  |  `BOOLEAN`  | 
|  `BLOB, BINARY, LONGVARBINARY`  |  `BLOB`  | 
|  `VARBINARY`  |  `STRING`  | 
|  `CLOB`  |  `STRING`  | 
|  其他類型 (包含與日期和時間相關的類型)  |  `STRING`  | 

字串值會傳遞至 Amazon Redshift 資料庫，並以隱含方式轉換為資料庫的資料類型。

**注意**  
目前，資料 API 不支援通用通用唯一識別碼 (UUID) 的陣列。

## 在呼叫 Amazon Redshift 資料 API 時執行含有參數的 SQL 陳述式
<a name="data-api-calling-considerations-parameters"></a>

您可以透過對 SQL 陳述式的各個部分使用參數來呼叫資料 API 操作，以控制提交給資料庫引擎的 SQL 文字。具名參數可讓您靈活地傳遞參數，而不必以硬式編碼的方式將其寫入 SQL 文字內。其可協助您重複使用 SQL 文字，並避免 SQL 隱碼攻擊問題。

下列範例顯示 `execute-statement` AWS CLI 命令之 `parameters` 欄位的具名參數。

```
--parameters "[{\"name\": \"id\", \"value\": \"1\"},{\"name\": \"address\", \"value\": \"Seattle\"}]"
```

在使用具名參數時，請考量下列事項：
+ 具名參數只能用來取代 SQL 陳述式中的值。
  + 您可以取代 INSERT 陳述式中的值，例如 `INSERT INTO mytable VALUES(:val1)`。

    具名參數可以是任何順序，並且可以在 SQL 文字中使用多次。前面範例中顯示的參數選項，`1` 和 `Seattle` 值會插入到資料表資料欄 `id` 和 `address`。在 SQL 文字中，您可以依下列方式指定具名參數：

    ```
    --sql "insert into mytable values (:id, :address)"
    ```
  + 您可以取代條件子句中的值，例如 `WHERE attr >= :val1`、`WHERE attr BETWEEN :val1 AND :val2` 和 `HAVING COUNT(attr) > :val`。
  + 您無法取代 SQL 陳述式中的資料欄名稱，例如 `SELECT column-name`、`ORDER BY column-name` 或 `GROUP BY column-name`。

    例如，下列 SELECT 陳述式會因為語法無效而失敗。

    ```
    --sql "SELECT :colname, FROM event" --parameters "[{\"name\": \"colname\", \"value\": \"eventname\"}]"
    ```

    如果使用錯誤的語法描述 (`describe-statement` 操作) 陳述式，則傳回的 `QueryString` 不會替代參數的資料欄名稱 (`"QueryString": "SELECT :colname, FROM event"`)，並且會回報錯誤 (錯誤：在 \$1"FROM\$1"\$1n Position: 12 或附近有語法錯誤)。
  + 您無法取代彙總函數中的資料欄名稱，例如 `COUNT(column-name)`、`AVG(column-name)` 或 `SUM(column-name)`。
  + 您無法取代 JOIN 子句中的資料欄名稱。
+ 當 SQL 執行時，資料會以隱含方式轉換為資料類型。如需資料類型轉換的相關資訊，請參閱《Amazon Redshift 資料庫開發人員指南》**中的[資料類型](https://docs.aws.amazon.com/redshift/latest/dg/c_Supported_data_types.html)。
+ 您無法將值設定為 NULL。資料 API 會將其解譯為常值字串 `NULL`。下列範例會將 `id` 取代為常值字串 `null`。不是 SQL NULL 值。

  ```
  --parameters "[{\"name\": \"id\", \"value\": \"null\"}]"
  ```
+ 您無法設定零長度的值。資料 API SQL 陳述式會失敗。下列範例會嘗試使用零長度的值來設定 `id`，並導致 SQL 陳述式失敗。

  ```
  --parameters "[{\"name\": \"id\", \"value\": \"\"}]"
  ```
+ 您無法使用參數在 SQL 陳述式中設定資料表名稱。資料 API 會遵循 JDBC `PreparedStatement` 的規則。
+ `describe-statement` 操作的輸出會傳回 SQL 陳述式的查詢參數。
+ 只有 `execute-statement` 操作會支援含有參數的 SQL 陳述式。

## 在呼叫 Amazon Redshift 資料 API 時執行含有等冪性字符的 SQL 陳述式
<a name="data-api-calling-considerations-idempotency"></a>

當您提出變動的 API 請求時，該請求一般會在操作的非同步工作流程完成之前傳回結果。即使請求已傳回結果，操作還是可能會在完成前就逾時或發生其他伺服器問題。這可能會讓您難以判斷請求是否成功，而且可能導致系統多次重試以確保操作能成功完成。但是，如果原始請求和後續的重試有成功，則操作會完成多次。這表示您可能會更新比預期數量還多的資源。

等冪性**可確保 API 請求不會完成超過一次。使用等冪請求時，如果原始請求成功完成，則任何後續的重試都會成功完成，而不必執行任何進一步的動作。資料 API `ExecuteStatement` 和 `BatchExecuteStatement` 操作具有選用的 `ClientToken` 等冪參數。`ClientToken` 會在 8 小時後到期。

**重要**  
如果您從 AWS SDK 呼叫 `ExecuteStatement`和 `BatchExecuteStatement`操作，它會自動產生用戶端字符，以便在重試時使用。在這種情況下，我們不建議將 `client-token` 參數與 `ExecuteStatement` 和 `BatchExecuteStatement` 操作搭配使用。檢視 CloudTrail 日誌以查看 `ClientToken`。如需 CloudTrail 日誌範例，請參閱 [Amazon Redshift 資料 API 範例](logging-with-cloudtrail.md#data-api-cloudtrail)。

下列`execute-statement` AWS CLI 命令說明冪等性的選用`client-token`參數。

```
aws redshift-data execute-statement 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --sql "select * from stl_query limit 1" 
    --database dev 
    --client-token b855dced-259b-444c-bc7b-d3e8e33f94g1
```

下表顯示您可能會從等冪 API 請求得到的一些常見回應，並提供重試建議。


| 回應 | 建議 | 說明 | 
| --- | --- | --- | 
|  200 (OK)  |  請勿重試  |  原始請求已成功完成。任何後續的重試都會成功傳回。  | 
|  400 系列的回應碼   |  請勿重試  |  請求有下列方面的問題： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/redshift/latest/mgmt/data-api.html) 如果請求涉及處於變更狀態過程的資源，則重試請求有可能會成功。  | 
|  500 系列的回應碼   |  重試  |  錯誤是由 AWS 伺服器端問題造成，通常是暫時性的。請使用適當的退避策略來重複請求。  | 

如需有關 Amazon Redshift 回應碼的資訊，請參閱《Amazon Redshift API 參考》**中的[常見錯誤](https://docs.aws.amazon.com/redshift/latest/APIReference/CommonErrors.html)。

## 在呼叫 Amazon Redshift 資料 API 時執行含有 session reuse 的 SQL 陳述式
<a name="data-api-calling-considerations-session-reuse"></a>

當您發出 API 請求來執行 SQL 陳述式時，SQL 執行所在的工作階段通常會在 SQL 完成時終止。為了讓工作階段在指定的秒數內保持作用中，資料 API `ExecuteStatement` 和 `BatchExecuteStatement` 操作具有選用的 `SessionKeepAliveSeconds` 參數。`SessionId` 回應欄位包含工作階段的識別，此識別可在後續 `ExecuteStatement` 和 `BatchExecuteStatement` 操作中使用。在後續呼叫中，您可以指定另一個 `SessionKeepAliveSeconds` 來變更閒置逾時時間。如果 `SessionKeepAliveSeconds` 未變更，則會保留初始閒置逾時設定。使用 session reuse 時，請考量下列事項：
+ `SessionKeepAliveSeconds` 的最大值為 24 小時。
+ 工作階段最長可持續 24 小時。24 小時過後，工作階段就會強制關閉，而進行中查詢也會終止。
+ 每個 Amazon Redshift 叢集或 Redshift Serverless 工作群組的工作階段數目上限為 500 個。
+ 您一次只能在一個工作階段中執行一個查詢。您需要等到查詢完成，才能在相同工作階段中執行下一個查詢。也就是說，您無法在提供的工作階段中平行執行查詢。
+ 資料 API 無法將特定工作階段的查詢排入佇列。

若要擷取呼叫 `ExecuteStatement` 和 `BatchExecuteStatement` 操作所使用的 `SessionId`，請呼叫 `DescribeStatement` 和 `ListStatements` 操作。

下列範例示範如何使用 `SessionKeepAliveSeconds` 和 `SessionId` 參數讓工作階段保持作用中並重複使用。首先，呼叫 `execute-statement` AWS CLI 命令，並將選用`session-keep-alive-seconds`參數設定為 `2`。

```
aws redshift-data execute-statement 
    --session-keep-alive-seconds 2 
    --sql "select 1" 
    --database dev 
    --workgroup-name mywg
```

回應會包含工作階段識別碼。

```
{
    "WorkgroupName": "mywg",
    "CreatedAt": 1703022996.436,
    "Database": "dev",
    "DbUser": "awsuser",
    "Id": "07c5ffea-76d6-4786-b62c-4fe3ef529680",
    "SessionId": "5a254dc6-4fc2-4203-87a8-551155432ee4"
}
```

然後，使用第一次呼叫`SessionId`傳回的 來呼叫 `execute-statement` AWS CLI 命令。選擇性地指定 `session-keep-alive-seconds` 參數並設定為 `10`，以變更閒置逾時值。

```
aws redshift-data execute-statement 
    --sql "select 1" 
    --session-id 5a254dc6-4fc2-4203-87a8-551155432ee4
    --session-keep-alive-seconds 10
```

## 擷取 SQL 陳述式的結果
<a name="data-api-calling-considerations-result-format"></a>

您可以根據結果格式，使用不同的資料 API 操作來擷取 SQL 結果。當您呼叫 `ExecuteStatement` 和 `BatchExecuteStatement` 操作時，您可以指定 JSON 或 CSV 格式的結果。如未指定，預設值會是 JSON。若要擷取 JSON 結果，請使用 `GetStatementResult` 操作。若要擷取 CSV 結果，請使用 `GetStatementResultV2` 操作。

以 JSON 格式傳回的結果是包含每一欄相關中繼資料的記錄。每一筆紀錄都會是 JSON 格式。例如，`GetStatementResult` 的回應看起來如下：

```
{
   "ColumnMetadata": [ 
      { 
         "isCaseSensitive": false,
         "isCurrency": false,
         "isSigned": true,
         "label": "?column?",
         "name": "?column?",
         "nullable": 1,
         "precision": 10,
         "scale": 0,
         "schemaName": "",
         "tableName": "",
         "typeName": "int4",
         "length": 0
      }
   ],
   "NextToken": "<token>",
   "Records": [
        [
            {
                "longValue": 1
            }
        ]
    ],
   "TotalNumRows": <number>
}
```

以 CSV 格式傳回的結果是包含每一欄相關中繼資料的記錄。結果會以 1 MB 區塊為單位傳回，每個區塊可以儲存任意數量的 CSV 格式資料列。每個請求最多傳回 15 MB 的結果。如果結果大於 15 MB，則會傳回下一頁記號以繼續擷取結果。例如，`GetStatementResultV2` 的回應看起來如下：

```
{
    "ColumnMetadata": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "?column?",
            "name": "?column?",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "",
            "typeName": "int4",
            "length": 0
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "?column?",
            "name": "?column?",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "",
            "typeName": "int4",
            "length": 0
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "?column?",
            "name": "?column?",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "",
            "typeName": "int4",
            "length": 0
        }
    ],
    "NextToken": "<token>",
    "Records": [
        [
            {
                "CSVRecords":"1,2,3\r\n4,5,6\r\n7,8,9\rn, .... 1MB" // First 1MB Chunk
            },
            {
                "CSVRecords":"1025,1026,1027\r\n1028,1029,1030\r\n....2MB" // Second 1MB chunk
            }
            ...
        ]
    ],
    "ResultFormat" : "CSV",
    "TotalNumRows": <number>
}
```

# 授權 Amazon Redshift 資料 API 的存取
<a name="data-api-access"></a>

若要存取資料 API，使用者必須獲得授權。您可以透過將受管政策 (即預先定義的 AWS Identity and Access Management (IAM) 政策) 新增至該使用者，來授權其存取資料 API。我們建議的最佳實務是，將許可政策附加到 IAM 角色，然後根據需要將其指派給使用者和群組。如需詳細資訊，請參閱 [Amazon Redshift 中的身分和存取管理](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-authentication-access-control.html)。若要查看受管政策允許和拒絕的許可，請參閱 IAM 主控台 ([https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/))。

# 設定 IAM 許可權限
<a name="data-api-iam"></a>

Amazon Redshift 會提供 `AmazonRedshiftDataFullAccess` 受管政策。此政策可提供 Amazon Redshift 資料 API 操作的完整存取權。此政策也允許對特定 Amazon Redshift 的存取範圍 AWS Secrets Manager，以及驗證和存取 Amazon Redshift 叢集或 Redshift Serverless 工作群組所需的 IAM API 操作。

您也可以建立自己的 IAM 政策，以允許存取特定資源。若要建立您的政策，請使用 `AmazonRedshiftDataFullAccess` 政策作為起始範本。建立政策後，將它新增給每一位需要資料 API 存取的使用者。

請考量與使用者相關聯之 IAM 政策的下列要求：
+ 如果您使用 AWS Secrets Manager 進行身分驗證，請確認政策允許使用 `secretsmanager:GetSecretValue`動作來擷取以金鑰 標記的秘密`RedshiftDataFullAccess`。
+ 如果您使用暫時憑證對叢集進行身分驗證，請確認政策允許對叢集中任何資料庫的資料庫使用者名稱 `redshift_data_api_user` 使用 `redshift:GetClusterCredentials` 動作。此使用者名稱必須已建立在資料庫中。
+ 如果您使用暫時憑證向無伺服器工作群組進行身分驗證，請確認政策允許使用 `redshift-serverless:GetCredentials` 動作來擷取以索引鍵 `RedshiftDataFullAccess` 標記的工作群組。資料庫使用者會以 1：1 映射至 source AWS Identity and Access Management (IAM) 身分。例如，使用者 sample\$1user 會映射至資料庫使用者 `IAM:sample_user`，而 IAM 角色 sample\$1role 會映射至 `IAMR:sample_role`。如需 IAM 身分的相關資訊，請參閱《IAM 使用者指南》中的 [IAM 身分 (使用者、使用者群組和角色)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html)。
+ IAM 動作 `redshift-data:GetStatementResult` 允許存取 `GetStatementResult` 和 `GetStatementResultV2` API 操作。

下列連結提供 *IAM 使用者指南* AWS Identity and Access Management 中有關 的詳細資訊。
+ 如需有關建立 IAM 角色的資訊，請參閱[建立 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)。
+ 如需有關建立 IAM 政策的資訊，請參閱[建立 IAM 政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html)。
+ 如需有關將 IAM 政策新增給使用者的資訊，請參閱[新增和移除 IAM 身分許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)。

## 在另一個帳戶擁有的叢集上執行查詢
<a name="data-api-run-query-on-others-cluster"></a>

若要在另一個帳戶擁有的叢集上執行查詢，擁有端帳戶必須提供資料 API 可在呼叫端帳戶中擔任的 IAM 角色。例如，假設帳戶 B 擁有帳戶 A 需要存取的叢集。帳戶 B 可將 AWS 受管政策連接至`AmazonRedshiftDataFullAccess`帳戶 B 的 IAM 角色。然後，帳戶 B 會使用信任政策來信任帳戶 A，如下所示：``

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111122223333:role/someRoleA"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

------

最後，帳戶 A 的 IAM 角色必須能夠擔任帳戶 B 的 IAM 角色。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::111122223333:role/someRoleB"
    }
}
```

------

## 指定 IAM 角色，將資源限制在 中的 Redshift Serverless 工作群組和 Amazon Redshift 叢集 AWS 帳戶
<a name="data-api-restrict-to-account"></a>

您可以在身分型政策中指定資源 ARN，以控制對 AWS 帳戶中 Redshift Serverless 工作群組和 Amazon Redshift 叢集的存取。此範例示範如何建立政策，以便僅允許所指定 AWS 帳戶中的工作群組和叢集存取資料 API。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "redshift-data:CancelStatement",
                "redshift-data:DescribeStatement",
                "redshift-data:GetStatementResult",
                "redshift-data:ListStatements"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "redshift-data:*",
            "Resource": [
                "arn:aws:redshift:us-east-1:111122223333:workgroup/*",
                "arn:aws:redshift:us-east-1:111122223333:cluster:*"
            ]
        }
    ]
}
```

------

## 設定 IAM 政策，以限制只有陳述式擁有者能夠存取 SQL 陳述式資訊
<a name="data-api-restrict-to-statement-owner"></a>

根據預設，Amazon Redshift 資料 API 會將呼叫 `ExecuteStatement` 和 `BatchExecuteStatement` 時使用的 IAM 角色視為 SQL 陳述式的擁有者。允許擔任該角色的任何人都可以存取 SQL 陳述式的相關資訊，包括其結果。若要限制只有特定擁有者的 IAM 角色工作階段才能存取 SQL 陳述式資訊，請新增條件 `redshift-data:statement-owner-iam-userid: "${aws:userid}"`。下列 IAM 政策會限制存取權。

------
#### [ JSON ]

****  

```
{
"Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "redshift-data:CancelStatement",
                "redshift-data:DescribeStatement",
                "redshift-data:GetStatementResult",
                "redshift-data:ListStatements"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "redshift-data:statement-owner-iam-userid": "${aws:userid}"
                }
            }
        }
    ]
}
```

------

您可以使用條件 `statement-owner-iam-userid` 搭配 `CancelStatement`、`DescribeStatement`、`GetStatementResult` 和 `ListStatements`。如需詳細資訊，請參閱 [Amazon Redshift 資料 API 定義的動作](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonredshiftdataapi.html#amazonredshiftdataapi-redshift-data_statement-owner-iam-userid)。

## 設定 IAM 政策以限制只有工作階段擁有者才能存取 SQL 結果
<a name="data-api-restrict-session-owner"></a>

根據預設，Amazon Redshift 資料 API 會將呼叫 `ExecuteStatement` 和 `BatchExecuteStatement` 時使用的 IAM 角色，視為執行 SQL 陳述式的資料庫工作階段的擁有者。允許擔任該角色的任何人都可以將查詢提交至資料庫工作階段。若要限制只有特定擁有者的 IAM 角色工作階段才能存取，請新增條件 ` redshift-data:session-owner-iam-userid: "${aws:userid}"`。下列 IAM 政策會限制存取權。

下列 IAM 政策僅允許工作階段擁有者取得陳述式結果。條件 `session-owner-iam-userid` 可用來限制只有指定的 `userid` 可存取資源。

------
#### [ JSON ]

****  

```
{
"Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [ 
                "redshift-data:ExecuteStatement",
                "redshift-data:BatchExecuteStatement"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "redshift-data:session-owner-iam-userid": "${aws:userid}"
                }
            }
        }
    ]
}
```

------

您可以使用條件 `session-owner-iam-userid` 搭配 `ExecuteStatement` 和 `BatchExecuteStatement`。如需詳細資訊，請參閱 [Amazon Redshift 資料 API 定義的動作](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonredshiftdataapi.html#amazonredshiftdataapi-redshift-data_statement-owner-iam-userid)。

# 在 中存放資料庫登入資料 AWS Secrets Manager
<a name="data-api-secrets"></a>

當您呼叫資料 API 時，您可以透過在 AWS Secrets Manager中使用機密來傳遞叢集或無伺服器工作群組的憑證。若要這樣傳遞登入資料，請指定秘密的名稱或秘密的 Amazon Resource Name (ARN)。

若要使用 Secrets Manager 來儲存憑證，您需要 `SecretManagerReadWrite` 受管政策許可。如需最低許可的詳細資訊，請參閱*AWS Secrets Manager 《 使用者指南*》中的[使用 Secrets Manager 建立和管理 AWS 秘密](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets.html)。

**將憑證儲存在 Amazon Redshift 叢集的機密中**

1. 使用 AWS Secrets Manager 主控台建立包含叢集登入資料的秘密：
   + 當您選擇**儲存新的機密**時，請選擇 **Redshift 叢集的憑證**。
   + 將**使用者名稱** (資料庫使用者)、**密碼**和**資料庫叢集** (叢集識別碼) 的值儲存在機密中。
   + 使用索引鍵 `RedshiftDataFullAccess` 標記機密。 AWS 受管政策`AmazonRedshiftDataFullAccess`僅允許`secretsmanager:GetSecretValue`以金鑰 標記的秘密執行 動作`RedshiftDataFullAccess`。

   如需說明，請參閱《AWS Secrets Manager 使用者指南》**中的[建立基本秘密](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)。

1. 使用 AWS Secrets Manager 主控台來檢視您建立之秘密的詳細資訊，或執行 `aws secretsmanager describe-secret` AWS CLI 命令。

   記下秘密的名稱和 ARN。您可以在呼叫資料 API 時使用這些資料。

**將憑證儲存在無伺服器工作群組的機密中**

1. 使用 AWS Secrets Manager AWS CLI 命令來存放包含無伺服器工作群組登入資料的秘密：
   + 在檔案中建立您的秘密，例如名為 `mycreds.json` 的 JSON 檔案。在檔案中提供**使用者名稱** (資料庫使用者) 和**密碼**的值。

     ```
     {
           "username": "myusername",
           "password": "mypassword"
     }
     ```
   + 將值儲存在機密中，並使用索引鍵 `RedshiftDataFullAccess` 標記機密。

     ```
     aws secretsmanager create-secret --name MyRedshiftSecret  --tags Key="RedshiftDataFullAccess",Value="serverless" --secret-string file://mycreds.json
     ```

     以下將顯示輸出。

     ```
     {
         "ARN": "arn:aws:secretsmanager:region:accountId:secret:MyRedshiftSecret-mvLHxf",
         "Name": "MyRedshiftSecret",
         "VersionId": "a1603925-e8ea-4739-9ae9-e509eEXAMPLE"
     }
     ```

   如需詳細資訊，請參閱《AWS Secrets Manager 使用者指南》**中的[使用 AWS CLI建立基本機密](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html#proc-create-api)。

1. 使用 AWS Secrets Manager 主控台來檢視您建立之秘密的詳細資訊，或執行 `aws secretsmanager describe-secret` AWS CLI 命令。

   記下秘密的名稱和 ARN。您可以在呼叫資料 API 時使用這些資料。

# 建立資料 API 的 Amazon VPC 端點 (AWS PrivateLink)
<a name="data-api-vpc-endpoint"></a>

Amazon Virtual Private Cloud (Amazon VPC) 可讓您在虛擬私有雲端 (VPC) 中安全地啟動 AWS 資源，例如 AWS Amazon Redshift 叢集和應用程式。 在虛擬私有雲端 (VPCs) 和服務之間 AWS PrivateLink 提供私有連線。您可以使用 AWS PrivateLink建立 VPC 端點，以根據 Amazon VPC 連接到不同帳戶和 VPCs 的服務。如需詳細資訊 AWS PrivateLink，請參閱《*Amazon Virtual Private Cloud 使用者指南*》中的 [VPC 端點服務 (AWS PrivateLink)](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html)。

您可以使用 Amazon VPC 端點呼叫資料 API。使用 Amazon VPC 端點可使 Amazon VPC 中的應用程式與資料 API 中的流量保持在 AWS 網路，而不使用公有 IP 地址。Amazon VPC 端點能協助您符合與限制公有網際網路連線相關的合規和法律需求。舉例來說，若使用 Amazon VPC 端點，就能讓在 Amazon EC2 執行個體上執行之應用程式和資料 API 的流量，只在包含兩者的 VPC 中傳送。

建立 Amazon VPC 端點之後就能開始使用，而不需要在應用程式中進行任何程式碼或組態變更。

**建立資料 API 的 Amazon VPC 端點**

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/vpc/](https://console.aws.amazon.com/vpc/)：// 開啟 Amazon VPC 主控台。

1. 選擇 **Endpoints (端點)**，然後選擇 **Create Endpoint (建立端點)**。

1. 在 **Create Endpoint** (建立端點) 頁面上，針對 **Service category** (服務類別) 選擇 **AWS services** ( 服務)。針對**服務名稱**，選擇 **redshift-data** (`com.amazonaws.region.redshift-data`)。

1. 針對 **VPC**，選擇要在其中建立端點的 VPC。

   選擇包含進行資料 API 呼叫之應用程式的 VPC。

1. 針對**子網路**，選擇執行您應用程式之 AWS 服務所使用的每個可用區域 (AZ) 的子網路。

   若要建立 Amazon VPC 端點，請指定可存取端點的私有 IP 地址範圍。若要執行此作業，請選擇每個可用區域的子網路。這麼做會將 VPC 端點限制為每個可用區域專屬的私有 IP 地址範圍，並且也會在每個可用區域中建立 Amazon VPC 端點。

1. 針對 **Enable DNS name (啟用 DNS 名稱)**，選取 **Enable for this endpoint (為此端點啟用)**。

   私有 DNS 會將標準資料 API DNS 主機名稱 (`https://redshift-data.region.amazonaws.com`) 解析為與您 Amazon VPC 端點專用 DNS 主機名稱相關的私有 IP 地址。因此，您可以使用 AWS CLI AWS SDKs存取資料 API VPC 端點，而不需要進行任何程式碼或組態變更來更新資料 API 端點 URL。

1. 針對 **Security group (安全群組)**，選擇要與 Amazon VPC 端點建立關聯的安全群組。

   選擇允許存取執行您應用程式之 AWS 服務的安全群組。舉例來說，若有 Amazon EC2 執行個體在執行您的應用程式，請選擇要允許存取 Amazon EC2 執行個體的安全群組。安全群組能讓您控制 VPC 中，資源流向 Amazon VPC 端點的流量。

1. 選擇**建立端點**。

建立端點之後，請選擇 中的連結 AWS 管理主控台 以檢視端點詳細資訊。

端點 **Details (詳細資訊)** 標籤會顯示建立 Amazon VPC 端點時產生的 DNS 主機名稱。

您可以使用標準端點 (`redshift-data.region.amazonaws.com`) 或其中一個 VPC 專用端點，來在 Amazon VPC 中呼叫資料 API。標準資料 API 端點會自動路由至 Amazon VPC 端點。因為私有 DNS 主機名稱在 Amazon VPC 端點建立時已啟用，所以會發生此路由。

當您在資料 API 呼叫中使用 Amazon VPC 端點時，應用程式與資料 API 間的所有流量都會維持在包含兩者的 Amazon VPC 中。您可以使用 Amazon VPC 端點進行任何類型的資料 API 呼叫。如需呼叫資料 API 的詳細資訊，請參閱[呼叫 Amazon Redshift 資料 API 時的考量](data-api.md#data-api-calling-considerations)。

# 連線到叢集時加入資料庫群組
<a name="data-api-dbgroups"></a>

資料庫群組是資料庫使用者的集合。您可以向群組授予資料庫權限。管理員可以設定 IAM 角色，以便在使用資料 API 執行 SQL 時將這些資料庫群組納入考量。如需資料庫群組的相關資訊，請參閱《Amazon Redshift 資料庫開發人員指南》**中的[群組](https://docs.aws.amazon.com/redshift/latest/dg/r_Groups.html)。

您可以設定資料 API 呼叫者的 IAM 角色，以便在資料 API 連線到叢集時，呼叫中指定的資料庫使用者會加入資料庫群組。只有在連線至已佈建的叢集時才支援此功能。連線至 Redshift Serverless 工作群組時則不支援。資料 API 呼叫者的 IAM 角色也必須允許 `redshift:JoinGroup` 動作。

請透過向 IAM 角色新增標籤來進行此設定。呼叫者 IAM 角色的管理員會新增標籤，標籤中包含資料庫群組清單的索引鍵 `RedshiftDbGroups` 和索引鍵值。此值是以冒號 (:) 分隔的資料庫群組名稱清單，總長度最多可有 256 個字元。您必須之前就已在連線的資料庫中定義好資料庫群組。如果在資料庫中找不到任何指定的群組，則會忽略該群組。例如，對於資料庫群組 `accounting` 和 `retail`，索引鍵-值為 `accounting:retail`。資料 API 會使用標籤索引鍵-值組 `{"Key":"RedshiftDbGroups","Value":"accounting:retail"}` 來判斷在呼叫資料 API 時，哪些資料庫群組會與所提供的資料庫使用者相關聯。

**聯結資料庫群組**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。

1. 在主控台導覽窗格中，選擇 **Roles** (角色)，然後選擇您要編輯的角色名稱。

1. 選擇**標籤**索引標籤，然後選擇**管理標籤**。

1. 選擇**新增標籤**，然後新增 **RedshiftDbGroups** 索引鍵和值 (此為 *database-groups-colon-separated* 清單)。

1. 選擇**儲存變更**。

   現在，當 IAM 主體 (附加了此 IAM 角色) 呼叫資料 API 時，指定的資料庫使用者便會加入 IAM 角色中指定的資料庫群組。

如需如何將標籤附加到主體 (包括 IAM 角色和 IAM 使用者) 的相關資訊，請參閱《IAM 使用者指南》**中的[標記 IAM 資源](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)。

# 使用資料 API 搭配可信身分傳播
<a name="data-api-trusted-identity-propagation"></a>

身為 Amazon Redshift 帳戶管理員，您可以將 Amazon Redshift 叢集或工作群組與 整合 AWS IAM Identity Center，這有助於透過單一登入來管理對 Amazon Redshift 的人力資源存取。如需詳細資訊，請參閱[設定與 AWS Amazon Redshift 的 IAM Identity Center 整合](redshift-iam-access-control-idp-connect-console.md)。Amazon Redshift Data API 支援將 IAM Identity Center 使用者身分傳播到 Amazon Redshift 叢集或工作群組，以及其他服務 AWS Lake Formation，例如鏈結下。您可以依照[使用受信任身分傳播以程式設計方式存取 AWS 服務](https://aws.amazon.com/blogs//security/access-aws-services-programmatically-using-trusted-identity-propagation/)中的步驟，使用資料 API 來設定和查詢。

當您使用來自身分增強型 IAM 角色工作階段的 IAM Identity Center 使用者身分呼叫資料 API 時，您只能存取使用相同 IAM Identity Center 使用者產生的陳述式和陳述式結果。例如，下列 AWS CLI 命令會呼叫 `execute-statement`操作，以執行具有信任身分傳播的 SQL 命令。

```
aws redshift-data execute-statement 
--sql "select current_user;" 
--cluster-id mycluster
--database dev
```

下列 AWS CLI 命令會呼叫 `batch-execute-statement`操作來執行兩個 SQL 命令。

```
aws redshift-data batch-execute-statement 
--sqls  "select current_user;"  "select current_date;"
--cluster-id mycluster
--database dev
```

若要存取由身分增強型 IAM 角色工作階段所提交具有 `cancel-statement`、`describe-statement`、`get-statement-result` 和 `get-statement-result-v2` 的陳述式，IAM Identity Center 使用者和 IAM 角色必須符合用於執行 `execute-statment` 或 `batch-execute-statement` 的憑證。例如，下列 AWS CLI 命令會取得 SQL 陳述式的結果。

```
aws redshift-data get-statement-result 
--id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```

若要列出陳述式，則必須提供 `cluster-identifier` 或 `workgroup-name` 參數，以確保 IAM Identity Center 使用者只能存取指派給他們的 Amazon Redshift IAM Identity Center 應用程式。例如，下列 AWS CLI 命令會列出特定叢集的陳述式。

```
aws redshift-data list-statements
--cluster-identifier mycluster
```

您也可以調用資料 API 操作，以使用可信身分傳播來存取叢集或工作群組中的資料庫物件。這包括 `list-databases`、`list-schemas`、`list-tables` 和 `describe-table` 操作。

IAM Identity Center 使用者發出的 API 呼叫可以在 AWS CloudTrail中追蹤。CloudTrail 事件的 `onBehalfOf` 區段會顯示 IAM Identity Center 使用者 ID 和身分存放區 ARN。下列範例示範 CloudTrail 事件的程式碼片段，顯示 `onBehalfOf` 區段中包含 IAM Identity Center 使用者 ID `a1b2c3d4-5678-90ab-cdef-EXAMPLE11111` 和身分存放區 ARN `arn:aws:identitystore::123456789012:identitystore/d-9067bc44d2`。

```
{
            "eventVersion":"1.10",
            "userIdentity":{
            "type":"AssumedRole",
            ...
            },
            "onBehalfOf":{
            "userId":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "identityStoreArn":"arn:aws:identitystore::123456789012:identitystore/d-9067bc44d2"
            }
            },
            "eventTime":"2025-01-13T04:46:27Z",
            "eventSource":"redshift-data.amazonaws.com",
            "eventName":"ExecuteStatement",
            "awsRegion":"us-east-1"
            }
```

您可以執行下列 SQL 命令來檢查 IAM Identity Center 使用者提交的查詢。在此範例中，Identity Center 中註冊的電子郵件為 `username@example.com`。

```
SELECT
    h.query_id,
    h.database_name,
    h.status,
    h.query_text,
    u.usename,
    h.start_time,
    h.end_time
FROM
    sys_query_history h
LEFT JOIN
    pg_user u
ON
    h.user_id = u.usesysid
where u.usename='awsidc:username@example.com'    
ORDER BY
    h.start_time DESC;
```

# 呼叫資料 API
<a name="data-api-calling"></a>

您可以呼叫資料 API 或 AWS CLI ，在您的叢集或無伺服器工作群組上執行 SQL 陳述式。在《Amazon Redshift 資料 API 參考》**中，用來執行 SQL 陳述式的主要操作是 [https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html) 和 [https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_BatchExecuteStatement.html](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_BatchExecuteStatement.html)。資料 API 支援 AWS SDK 支援的程式設計語言。如需這些語言的相關資訊，請參閱[用來在 AWS上進行建置的工具](https://aws.amazon.com/tools/)。

若要查看呼叫資料 API 的程式碼範例，請參閱 *GitHub* 中的[開始使用 Redshift 資料 API](https://github.com/aws-samples/getting-started-with-amazon-redshift-data-api#getting-started-with-redshift-data-api)。此儲存庫具有使用 從 Amazon EC2 AWS Glue Data Catalog和 Amazon SageMaker 執行期 AWS Lambda 存取 Amazon Redshift 資料的範例。範例程式設計語言包括 Python、Go、Java 和 Javascript。

您可以使用 AWS CLI呼叫資料 API。

下列範例使用 AWS CLI 呼叫資料 API。若要執行範例，請編輯參數值以符合您的環境。許多範例會提供 `cluster-identifier` 來針對叢集執行。當您針對無伺服器工作群組執行時，請改為提供 `workgroup-name`。這些範例會示範一些資料 API 操作。如需詳細資訊，請參閱 *AWS CLI 命令參考*。

下列範例中的命令已經過分割和格式化，以方便您閱讀。並非所有參數和回應都會在所有範例中顯示。如需完整請求語法、請求參數、回應語法和回應元素的 API 定義，請參閱 [Amazon Redshift 資料 API 參考](https://docs.aws.amazon.com/redshift-data/latest/APIReference/)。

# 將 SQL 陳述式傳遞至 Amazon Redshift 資料倉儲
<a name="pass-sql-statements"></a>

本頁中的範例涵蓋將 SQL 陳述式傳遞至資料倉儲的不同方式

## 執行 SQL 陳述式
<a name="data-api-calling-cli-execute-statement"></a>

若要執行 SQL 陳述式，請使用 `aws redshift-data execute-statement` AWS CLI 命令。

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，並傳回識別符以擷取結果。此範例會使用 AWS Secrets Manager 身分驗證方法。

```
aws redshift-data execute-statement 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --sql "select * from stl_query limit 1" 
    --database dev
```

以下是回應的範例。

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": 1598323175.823,
    "Database": "dev",
    "Id": "c016234e-5c6c-4bc5-bb16-2c5b8ff61814",
    "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn"
}
```

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，並傳回識別符以擷取結果。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data execute-statement 
    --db-user myuser 
    --cluster-identifier mycluster-test 
    --database dev 
    --sql "select * from stl_query limit 1"
```

以下是回應的範例。

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": 1598306924.632,
    "Database": "dev",
    "DbUser": "myuser",
    "Id": "d9b6c0c9-0747-4bf4-b142-e8883122f766"
}
```

下列 AWS CLI 命令會對無伺服器工作群組執行 SQL 陳述式，並傳回識別符以擷取結果。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data execute-statement 
    --database dev 
    --workgroup-name myworkgroup 
    --sql "select 1;"
```

以下是回應的範例。

```
{
 "CreatedAt": "2022-02-11T06:25:28.748000+00:00",
 "Database": "dev",
 "DbUser": "IAMR:RoleName",
 "Id": "89dd91f5-2d43-43d3-8461-f33aa093c41e",
 "WorkgroupName": "myworkgroup"
}
```

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，並傳回識別符以擷取結果。此範例會使用 AWS Secrets Manager 身分驗證方法和等冪性字符。

```
aws redshift-data execute-statement 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --sql "select * from stl_query limit 1" 
    --database dev 
    --client-token b855dced-259b-444c-bc7b-d3e8e33f94g1
```

以下是回應的範例。

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": 1598323175.823,
    "Database": "dev",
    "Id": "c016234e-5c6c-4bc5-bb16-2c5b8ff61814",
    "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn"
}
```

## 執行含有參數的 SQL 陳述式
<a name="data-api-calling-cli-execute-statement-parameters"></a>

若要執行 SQL 陳述式，請使用 `aws redshift-data execute-statement` AWS CLI 命令。

 下列 AWS CLI 命令會對叢集執行 SQL 陳述式，並傳回識別符以擷取結果。此範例會使用 AWS Secrets Manager 身分驗證方法。SQL 文字有具名參數 `distance`。在此案例中，述詞中使用的距離是 `5`。在 SELECT 陳述式中，資料欄名稱的具名參數只能在述詞中使用。SQL 陳述式的具名參數值會於 `parameters` 選項中指定。

```
aws redshift-data execute-statement 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --sql "SELECT ratecode FROM demo_table WHERE trip_distance > :distance"  
    --parameters "[{\"name\": \"distance\", \"value\": \"5\"}]"
    --database dev
```

以下是回應的範例。

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": 1598323175.823,
    "Database": "dev",
    "Id": "c016234e-5c6c-4bc5-bb16-2c5b8ff61814",
    "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn"
}
```

下列範例會使用來自範例資料庫的 `EVENT` 資料表。如需詳細資訊，請參閱《Amazon Redshift 資料庫開發人員指南》**中的 [EVENT 資料表](https://docs.aws.amazon.com/redshift/latest/dg/r_eventtable.html)。

如果資料庫中還沒有 `EVENT` 資料表，您可以使用資料 API 加以建立，如下所示：

```
aws redshift-data execute-statement 
--database dev
--cluster-id mycluster-test
--db-user awsuser
--sql "create table event( eventid integer not null distkey, 
                           venueid smallint not null, 
                           catid smallint not null, 
                           dateid smallint not null sortkey, 
                           eventname varchar(200), 
                           starttime timestamp)"
```

下列命令會在 `EVENT` 資料表中插入一個資料列。

```
aws redshift-data execute-statement 
--database dev
--cluster-id mycluster-test
--db-user awsuser 
--sql "insert into event values(:eventid, :venueid::smallint, :catid, :dateid, :eventname, :starttime)" 
--parameters "[{\"name\": \"eventid\", \"value\": \"1\"}, {\"name\": \"venueid\", \"value\": \"1\"}, 
               {\"name\": \"catid\", \"value\": \"1\"}, 
               {\"name\": \"dateid\", \"value\": \"1\"}, 
               {\"name\": \"eventname\", \"value\": \"event 1\"}, 
               {\"name\": \"starttime\", \"value\": \"2022-02-22\"}]"
```

下列命令會在 `EVENT` 資料表中插入第二個資料列。此範例示範下列操作：
+ 名為 `id` 的參數會在 SQL 文字中使用四次。
+ 在插入參數 `starttime` 時會自動套用隱含類型轉換。
+ `venueid` 資料欄是轉換為 SMALLINT 資料類型的類型。
+ 代表 DATE 資料類型的字元字串會隱含地轉換成 TIMESTAMP 資料類型。
+ 您可以在 SQL 文字中使用註解。

```
aws redshift-data execute-statement 
--database dev
--cluster-id mycluster-test
--db-user awsuser 
--sql "insert into event values(:id, :id::smallint, :id, :id, :eventname, :starttime) /*this is comment, and it won't apply parameterization for :id, :eventname or :starttime here*/" 
--parameters "[{\"name\": \"eventname\", \"value\": \"event 2\"}, 
               {\"name\": \"starttime\", \"value\": \"2022-02-22\"}, 
               {\"name\": \"id\", \"value\": \"2\"}]"
```

下列範例顯示所插入的兩個資料列：

```
 eventid | venueid | catid | dateid | eventname |      starttime
---------+---------+-------+--------+-----------+---------------------
       1 |       1 |     1 |      1 | event 1   | 2022-02-22 00:00:00
       2 |       2 |     2 |      2 | event 2   | 2022-02-22 00:00:00
```

下列命令會在 WHERE 子句中使用具名參數來擷取 `eventid` 是 `1` 的資料列。

```
aws redshift-data execute-statement 
--database dev
--cluster-id mycluster-test
--db-user awsuser 
--sql "select * from event where eventid=:id"
--parameters "[{\"name\": \"id\", \"value\": \"1\"}]"
```

執行下列命令以取得上一個 SQL 陳述式的 SQL 結果：

```
aws redshift-data get-statement-result --id 7529ad05-b905-4d71-9ec6-8b333836eb5a        
```

提供下列結果：

```
{
    "Records": [
        [
            {
                "longValue": 1
            },
            {
                "longValue": 1
            },
            {
                "longValue": 1
            },
            {
                "longValue": 1
            },
            {
                "stringValue": "event 1"
            },
            {
                "stringValue": "2022-02-22 00:00:00.0"
            }
        ]
    ],
    "ColumnMetadata": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "eventid",
            "length": 0,
            "name": "eventid",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "event",
            "typeName": "int4"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "venueid",
            "length": 0,
            "name": "venueid",
            "nullable": 0,
            "precision": 5,
            "scale": 0,
            "schemaName": "public",
            "tableName": "event",
            "typeName": "int2"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "catid",
            "length": 0,
            "name": "catid",
            "nullable": 0,
            "precision": 5,
            "scale": 0,
            "schemaName": "public",
            "tableName": "event",
            "typeName": "int2"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "dateid",
            "length": 0,
            "name": "dateid",
            "nullable": 0,
            "precision": 5,
            "scale": 0,
            "schemaName": "public",
            "tableName": "event",
            "typeName": "int2"
        },
        {
            "isCaseSensitive": true,
            "isCurrency": false,
            "isSigned": false,
            "label": "eventname",
            "length": 0,
            "name": "eventname",
            "nullable": 1,
            "precision": 200,
            "scale": 0,
            "schemaName": "public",
            "tableName": "event",
            "typeName": "varchar"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "label": "starttime",
            "length": 0,
            "name": "starttime",
            "nullable": 1,
            "precision": 29,
            "scale": 6,
            "schemaName": "public",
            "tableName": "event",
            "typeName": "timestamp"
        }
    ],
    "TotalNumRows": 1
}
```

## 執行多個 SQL 陳述式
<a name="data-api-calling-cli-batch-execute-statement"></a>

若要使用一個命令執行多個 SQL 陳述式，請使用 `aws redshift-data batch-execute-statement` AWS CLI 命令。

下列 AWS CLI 命令會對叢集執行三個 SQL 陳述式，並傳回識別符來擷取結果。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data batch-execute-statement 
    --db-user myuser 
    --cluster-identifier mycluster-test 
    --database dev 
    --sqls "set timezone to BST" "select * from mytable" "select * from another_table"
```

以下是回應的範例。

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": 1598306924.632,
    "Database": "dev",
    "DbUser": "myuser",
    "Id": "d9b6c0c9-0747-4bf4-b142-e8883122f766"
}
```

# 列出有關 SQL 陳述式的中繼資料
<a name="data-api-calling-cli-list-statements"></a>

若要列出 SQL 陳述式的中繼資料，請使用 `aws redshift-data list-statements` AWS CLI 命令。執行此命令的授權取決於呼叫者的 IAM 許可。

下列 AWS CLI 命令會列出執行的 SQL 陳述式。

```
aws redshift-data list-statements 
    --status ALL
```

以下是回應的範例。

```
{
    "Statements": [
        {
            "CreatedAt": 1598306924.632,
            "Id": "d9b6c0c9-0747-4bf4-b142-e8883122f766",
            "QueryString": "select * from stl_query limit 1",
            "Status": "FINISHED",
            "UpdatedAt": 1598306926.667
        },
        {
            "CreatedAt": 1598311717.437,
            "Id": "e0ebd578-58b3-46cc-8e52-8163fd7e01aa",
            "QueryString": "select * from stl_query limit 1",
            "Status": "FAILED",
            "UpdatedAt": 1598311719.008
        },
        {
            "CreatedAt": 1598313683.65,
            "Id": "c361d4f7-8c53-4343-8c45-6b2b1166330c",
            "QueryString": "select * from stl_query limit 1",
            "Status": "ABORTED",
            "UpdatedAt": 1598313685.495
        },
        {
            "CreatedAt": 1598306653.333,
            "Id": "a512b7bd-98c7-45d5-985b-a715f3cfde7f",
            "QueryString": "select 1",
            "Status": "FINISHED",
            "UpdatedAt": 1598306653.992
        }
    ]
}
```

# 描述有關 SQL 陳述式的中繼資料
<a name="data-api-calling-cli-describe-statement"></a>

若要取得 SQL 陳述式中繼資料的說明，請使用 `aws redshift-data describe-statement` AWS CLI 命令。執行此命令的授權取決於呼叫者的 IAM 許可。

下列 AWS CLI 命令說明 SQL 陳述式。

```
aws redshift-data describe-statement 
    --id d9b6c0c9-0747-4bf4-b142-e8883122f766
```

以下是回應的範例。

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": 1598306924.632,
    "Duration": 1095981511,
    "Id": "d9b6c0c9-0747-4bf4-b142-e8883122f766",
    "QueryString": "select * from stl_query limit 1",
    "RedshiftPid": 20859,
    "RedshiftQueryId": 48879,
    "ResultRows": 1,
    "ResultSize": 4489,
    "Status": "FINISHED",
    "UpdatedAt": 1598306926.667
}
```

以下是在執行含有多個 SQL 陳述式的 `batch-execute-statement` 命令後的 `describe-statement` 回應範例。

```
{
    "ClusterIdentifier": "mayo",
    "CreatedAt": 1623979777.126,
    "Duration": 6591877,
    "HasResultSet": true,
    "Id": "b2906c76-fa6e-4cdf-8c5f-4de1ff9b7652",
    "RedshiftPid": 31459,
    "RedshiftQueryId": 0,
    "ResultRows": 2,
    "ResultSize": 22,
    "Status": "FINISHED",
    "SubStatements": [
        {
            "CreatedAt": 1623979777.274,
            "Duration": 3396637,
            "HasResultSet": true,
            "Id": "b2906c76-fa6e-4cdf-8c5f-4de1ff9b7652:1",
            "QueryString": "select 1;",
            "RedshiftQueryId": -1,
            "ResultRows": 1,
            "ResultSize": 11,
            "Status": "FINISHED",
            "UpdatedAt": 1623979777.903
        },
        {
            "CreatedAt": 1623979777.274,
            "Duration": 3195240,
            "HasResultSet": true,
            "Id": "b2906c76-fa6e-4cdf-8c5f-4de1ff9b7652:2",
            "QueryString": "select 2;",
            "RedshiftQueryId": -1,
            "ResultRows": 1,
            "ResultSize": 11,
            "Status": "FINISHED",
            "UpdatedAt": 1623979778.076
        }
    ],
    "UpdatedAt": 1623979778.183
}
```

# 擷取 SQL 陳述式的結果
<a name="data-api-calling-cli-get-statement-result"></a>

若要從執行的 SQL 陳述式擷取結果，請使用 `redshift-data get-statement-result`或 `redshift-data get-statement-result-v2` AWS CLI 命令。來自 `get-statement-result` 的結果為 JSON 格式。來自 `get-statement-result-v2` 的結果為 CSV 格式。您可以提供所收到的 `Id` 以回應 `execute-statement` 或 `batch-execute-statement`。由 `batch-execute-statement` 執行的 SQL 陳述式的 `Id` 值可以在 `describe-statement` 的結果中擷取，並且會加上由冒號和序號組成的字尾 (例如 `b2906c76-fa6e-4cdf-8c5f-4de1ff9b7652:2`)。如果您使用 `batch-execute-statement` 執行多個 SQL 陳述式，則每個 SQL 陳述式都會有一個 `Id` 值，如 `describe-statement` 中所示。執行此命令的授權取決於呼叫者的 IAM 許可。

下列陳述式會傳回由 `ResultFormat` 預設為 `JSON` 的 `execute-statement` 所執行 SQL 陳述式的結果。若要擷取結果，請呼叫 `get-statement-result` 操作。

```
aws redshift-data get-statement-result 
    --id d9b6c0c9-0747-4bf4-b142-e8883122f766
```

下列陳述式會傳回由 `batch-execute-statement` 執行的第二個 SQL 陳述式的結果。

```
aws redshift-data get-statement-result 
    --id b2906c76-fa6e-4cdf-8c5f-4de1ff9b7652:2
```

以下是呼叫 `get-statement-result` 的回應範例，其中 SQL 結果會在回應的 `Records` 索引鍵中以 JSON 格式傳回。

```
{
    "ColumnMetadata": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "userid",
            "length": 0,
            "name": "userid",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int4"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "query",
            "length": 0,
            "name": "query",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int4"
        },
        {
            "isCaseSensitive": true,
            "isCurrency": false,
            "isSigned": false,
            "label": "label",
            "length": 0,
            "name": "label",
            "nullable": 0,
            "precision": 320,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "bpchar"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "xid",
            "length": 0,
            "name": "xid",
            "nullable": 0,
            "precision": 19,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int8"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "pid",
            "length": 0,
            "name": "pid",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int4"
        },
        {
            "isCaseSensitive": true,
            "isCurrency": false,
            "isSigned": false,
            "label": "database",
            "length": 0,
            "name": "database",
            "nullable": 0,
            "precision": 32,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "bpchar"
        },
        {
            "isCaseSensitive": true,
            "isCurrency": false,
            "isSigned": false,
            "label": "querytxt",
            "length": 0,
            "name": "querytxt",
            "nullable": 0,
            "precision": 4000,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "bpchar"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "label": "starttime",
            "length": 0,
            "name": "starttime",
            "nullable": 0,
            "precision": 29,
            "scale": 6,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "timestamp"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "label": "endtime",
            "length": 0,
            "name": "endtime",
            "nullable": 0,
            "precision": 29,
            "scale": 6,
            "schemaName": "",
            "tableName": "stll_query",
            "type": 93,
            "typeName": "timestamp"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "aborted",
            "length": 0,
            "name": "aborted",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int4"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "insert_pristine",
            "length": 0,
            "name": "insert_pristine",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int4"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "concurrency_scaling_status",
            "length": 0,
            "name": "concurrency_scaling_status",
            "nullable": 0,
            "precision": 10,
            "scale": 0,
            "schemaName": "",
            "tableName": "stll_query",
            "typeName": "int4"
        }
    ],
    "Records": [
        [
            {
                "longValue": 1
            },
            {
                "longValue": 3
            },
            {
                "stringValue": "health"
            },
            {
                "longValue": 1023
            },
            {
                "longValue": 15279
            },
            {
                "stringValue": "dev"
            },
            {
                "stringValue": "select system_status from stv_gui_status;"
            },
            {
                "stringValue": "2020-08-21 17:33:51.88712"
            },
            {
                "stringValue": "2020-08-21 17:33:52.974306"
            },
            {
                "longValue": 0
            },
            {
                "longValue": 0
            },
            {
                "longValue": 6
            }
        ]
    ],
    "TotalNumRows": 1
}
```

下列範例顯示 `execute-statement` 執行的 SQL 陳述式，且傳回的結果為 JSON 格式。資料表 `testingtable` 有三個整數欄 (col1、col2、col3)，而且有三列的值 (1、2、3)、(4、5、6) 和 (7、8、9)。

```
aws redshift-data execute-statement 
    --database dev 
    --sql "SELECT col1, col2, col3 FROM testingtable" 
    --cluster-id mycluster-test 
    --result-format JSON
```

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": "2024-04-02T16:45:25.144000+00:00",
    "Database": "dev",
    "DbUser": "IAMR:Administrator",
    "Id": "d468d942-6df9-4f85-8ae3-bac01a61aec3"
}
```

以下是呼叫 `get-statement-result` 的回應範例，其中 SQL 結果會在回應的 `Records` 索引鍵中以 JSON 格式傳回。

```
aws redshift-data get-statement-result
    --id d468d942-6df9-4f85-8ae3-bac01a61aec3
```

```
{
    "Records": [
        [
            {
                "longValue": 1
            },
            {
                "longValue": 2
            },
            {
                "longValue": 3
            }
        ],
        [
            {
                "longValue": 4
            },
            {
                "longValue": 5
            },
            {
                "longValue": 6
            }
        ],
        [
            {
                "longValue": 7
            },
            {
                "longValue": 8
            },
            {
                "longValue": 9
            }
        ]
    ],
    "ColumnMetadata": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "col1",
            "name": "col1",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "testingtable",
            "typeName": "int4",
            "length": 0
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "col2",
            "name": "col2",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "testingtable",
            "typeName": "int4",
            "length": 0
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "col3",
            "name": "col3",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "testingtable",
            "typeName": "int4",
            "length": 0
        }
    ],
    "TotalNumRows": 3
}
```

下列範例顯示 `execute-statement` 執行的 SQL 陳述式，且傳回的結果為 CSV 格式。資料表 `testingtable` 有三個整數欄 (col1、col2、col3)，而且有三列的值 (1、2、3)、(4、5、6) 和 (7、8、9)。

```
aws redshift-data execute-statement 
    --database dev 
    --sql "SELECT col1, col2, col3 FROM testingtable" 
    --cluster-id mycluster-test 
    --result-format CSV
```

```
{
    "ClusterIdentifier": "mycluster-test",
    "CreatedAt": "2024-04-02T16:45:25.144000+00:00",
    "Database": "dev",
    "DbUser": "IAMR:Administrator",
    "Id": "d468d942-6df9-4f85-8ae3-bac01a61aec3"
}
```

以下是呼叫 `get-statement-result-v2` 的回應範例，其中 SQL 結果會在回應的 `Records` 索引鍵中以 CSV 格式傳回。資料列會以換行和新行 (\$1r\$1n) 符號分隔。`Records` 中傳回的第一列為欄標頭。以 CSV 格式傳回的結果會以 1 MB 為單位傳回，且每個區塊可以儲存最大 1MB 的任意列數。

```
aws redshift-data get-statement-result-v2
    --id d468d942-6df9-4f85-8ae3-bac01a61aec3
```

```
{
    "Records": [
        {
            "CSVRecords": "col1,col2,col3\r\n1,2,3\r\n4,5,6\r\n7,8,9\r\n"
        }
    ],
    "ColumnMetadata": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "col1",
            "name": "col1",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "testingtable",
            "typeName": "int4",
            "length": 0
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "col2",
            "name": "col2",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "testingtable",
            "typeName": "int4",
            "length": 0
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": true,
            "label": "col3",
            "name": "col3",
            "nullable": 1,
            "precision": 10,
            "scale": 0,
            "schemaName": "public",
            "tableName": "testingtable",
            "typeName": "int4",
            "length": 0
        }
    ],
    "TotalNumRows": 3,
    "ResultFormat": "csv"
}
```

# 描述資料表
<a name="data-api-calling-cli-describe-table"></a>

若要取得描述資料表的中繼資料，請使用 `aws redshift-data describe-table` AWS CLI 命令。

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，並傳回描述資料表的中繼資料。此範例使用 AWS Secrets Manager 身分驗證方法。

```
aws redshift-data describe-table  
    --cluster-identifier mycluster-test 
    --database dev 
    --schema information_schema 
    --table sql_features 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn
```

以下是回應的範例。

```
{
    "ColumnList": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "feature_id",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "feature_name",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        }     
    ]
}
```

下列 AWS CLI 命令會對描述資料表的叢集執行 SQL 陳述式。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data describe-table 
    --db-user myuser 
    --cluster-identifier mycluster-test 
    --database dev 
    --schema information_schema 
    --table sql_features
```

以下是回應的範例。

```
{
    "ColumnList": [
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "feature_id",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "feature_name",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "sub_feature_id",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "sub_feature_name",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "is_supported",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "is_verified_by",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        },
        {
            "isCaseSensitive": false,
            "isCurrency": false,
            "isSigned": false,
            "length": 2147483647,
            "name": "comments",
            "nullable": 1,
            "precision": 2147483647,
            "scale": 0,
            "schemaName": "information_schema",
            "tableName": "sql_features",
            "typeName": "character_data"
        }
    ]
}
```

# 列出叢集中的資料庫
<a name="data-api-calling-cli-list-databases"></a>

若要列出叢集中的資料庫，請使用 `aws redshift-data list-databases` AWS CLI 命令。

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，以列出資料庫。此範例使用 AWS Secrets Manager 身分驗證方法。

```
aws redshift-data list-databases  

    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --database dev
```

以下是回應的範例。

```
{
    "Databases": [
        "dev"
    ]
}
```

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，以列出資料庫。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data list-databases  
    --db-user myuser 
    --cluster-identifier mycluster-test 
    --database dev
```

以下是回應的範例。

```
{
    "Databases": [
        "dev"
    ]
}
```

# 列出資料庫中的結構描述
<a name="data-api-calling-cli-list-schemas"></a>

若要列出資料庫中的結構描述，請使用 `aws redshift-data list-schemas` AWS CLI 命令。

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，以列出資料庫中的結構描述。此範例使用 AWS Secrets Manager 身分驗證方法。

```
aws redshift-data list-schemas 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --database dev
```

以下是回應的範例。

```
{
    "Schemas": [
        "information_schema",
        "pg_catalog",
        "pg_internal",
        "public"
    ]
}
```

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，以列出資料庫中的結構描述。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data list-schemas 
    --db-user mysuser 
    --cluster-identifier mycluster-test 
    --database dev
```

以下是回應的範例。

```
{
    "Schemas": [
        "information_schema",
        "pg_catalog",
        "pg_internal",
        "public"
    ]
}
```

# 列出資料庫中的資料表
<a name="data-api-calling-cli-list-tables"></a>

若要列出資料庫中的資料表，請使用 `aws redshift-data list-tables` AWS CLI 命令。

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，以列出資料庫中的資料表。此範例使用 AWS Secrets Manager 身分驗證方法。

```
aws redshift-data list-tables 
    --secret-arn arn:aws:secretsmanager:us-west-2:123456789012:secret:myuser-secret-hKgPWn 
    --cluster-identifier mycluster-test 
    --database dev 
    --schema information_schema
```

以下是回應的範例。

```
{
    "Tables": [
        {
            "name": "sql_features",
            "schema": "information_schema",
            "type": "SYSTEM TABLE"
        },
        {
            "name": "sql_implementation_info",
            "schema": "information_schema",
            "type": "SYSTEM TABLE"
        }
}
```

下列 AWS CLI 命令會對叢集執行 SQL 陳述式，以列出資料庫中的資料表。此範例使用暫時憑證身分驗證方法。

```
aws redshift-data list-tables  

     --db-user myuser 
     --cluster-identifier mycluster-test 
     --database dev 
     --schema information_schema
```

以下是回應的範例。

```
{
    "Tables": [
        {
            "name": "sql_features",
            "schema": "information_schema",
            "type": "SYSTEM TABLE"
        },
        {
            "name": "sql_implementation_info",
            "schema": "information_schema",
            "type": "SYSTEM TABLE"
        }
    ]
}
```

# 針對 Amazon Redshift 資料 API 的問題進行故障診斷
<a name="data-api-troubleshooting"></a>

請使用下列標題包含常見錯誤訊息的章節，協助針對您在使用資料 API 時所發生的問題進行故障診斷。

**Topics**
+ [查詢封包過大](#data-api-troubleshooting-packet-too-large)
+ [資料庫回應超過大小上限](#data-api-troubleshooting-response-size-too-large)

## 查詢封包過大
<a name="data-api-troubleshooting-packet-too-large"></a>

如果您看到錯誤，內容指出查詢的封包太大，這一般是因為針對資料列傳回的結果集太大。針對資料庫傳回結果集中的每個資料列，資料 API 的大小上限為每個資料列 64 KB。

若要解決此問題，請確定結果集的每個資料列都是 64 KB 或更小。

## 資料庫回應超過大小上限
<a name="data-api-troubleshooting-response-size-too-large"></a>

如果您看到錯誤，內容指出資料庫回應超過大小限制，這一般是因為資料庫傳回的結果集大小太大。資料庫傳回的結果集中的資料 API 限制為 500 MB。

若要解決此問題，請確保對資料 API 的呼叫傳回 500 MB 或更少的資料。如果您需要傳回超過 500 MB，您可以使用查詢中的 `LIMIT`子句執行多個陳述式呼叫。

# 使用 Amazon EventBridge 來排程 Amazon Redshift 資料 API 操作
<a name="data-api-calling-event-bridge"></a>

您可以建立會比對所選事件並將其路由到目標以採取行動的規則。您也可以使用規則對預定的排程採取行動。如需詳細資訊，請參閱[「Amazon EventBridge 使用者指南」](https://docs.aws.amazon.com/eventbridge/latest/userguide/)。

若要使用 EventBridge 來排程資料 API 操作，相關聯的 IAM 角色必須信任 CloudWatch Events 的主體 (events.amazonaws.com)。此角色應該要有已附加之受管政策 `AmazonEventBridgeFullAccess` 的對等項目。其也應該要有由資料 API 管理的 `AmazonRedshiftDataFullAccess` 政策許可。您可以在 IAM 主控台上使用這些許可建立 IAM 角色。在 IAM 主控台上建立角色時，請選擇 CloudWatch Events AWS 的服務信任實體。在 EventBridge 目標的 `RoleArn` JSON 值中指定 IAM 角色。如需建立 IAM 角色的詳細資訊，請參閱《*IAM 使用者指南*》中的[為 AWS 服務建立角色 （主控台）](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#roles-creatingrole-service-console)。

您在 Amazon EventBridge 中所建立規則的 `name` 必須符合 `RedshiftDataParameters` 中的 `StatementName`。

下列範例顯示使用單一或多個 SQL 陳述式，以及使用 Amazon Redshift 叢集或 Amazon Redshift Serverless 工作群組作為資料倉儲來建立 EventBridge 規則的各種變化。

## 使用單一 SQL 陳述式和叢集來進行呼叫
<a name="data-api-calling-event-bridge-sql-cluster"></a>

下列範例使用 AWS CLI 建立 EventBridge 規則，用於對 Amazon Redshift 叢集執行 SQL 陳述式。

```
aws events put-rule 
--name test-redshift-cluster-data 
--schedule-expression "rate(1 minute)"
```

然後，會建立 EventBridge 目標以便依照規則中指定的排程來執行。

```
aws events put-targets 
--cli-input-json file://data.json
```

data.json 輸入檔案如下。`Sql` JSON 索引鍵表示有單一 SQL 陳述式。`Arn` JSON 值包含叢集識別碼。`RoleArn` JSON 值包含用來執行 SQL 的 IAM 角色，如先前所述。

```
{
    "Rule": "test-redshift-cluster-data",
    "EventBusName": "default",
    "Targets": [
        {
            "Id": "2",
            "Arn": "arn:aws:redshift:us-east-1:123456789012:cluster:mycluster",
            "RoleArn": "arn:aws:iam::123456789012:role/Administrator",
            "RedshiftDataParameters": {
                "Database": "dev",
                "DbUser": "root",
                "Sql": "select 1;",
                "StatementName": "test-redshift-cluster-data",
                "WithEvent": true
            }
        }
    ]
}
```

## 使用單一 SQL 陳述式和工作群組來進行呼叫
<a name="data-api-calling-event-bridge-sql-workgroup"></a>

下列範例使用 AWS CLI 建立 EventBridge 規則，用於對 Amazon Redshift Serverless 工作群組執行 SQL 陳述式。

```
aws events put-rule 
--name  test-redshift-serverless-workgroup-data 
--schedule-expression "rate(1 minute)"
```

然後，會建立 EventBridge 目標以便依照規則中指定的排程來執行。

```
aws events put-targets 
--cli-input-json file://data.json
```

data.json 輸入檔案如下。`Sql` JSON 索引鍵表示有單一 SQL 陳述式。`Arn` JSON 值包含工作群組名稱。`RoleArn` JSON 值包含用來執行 SQL 的 IAM 角色，如先前所述。

```
{
    "Rule": "test-redshift-serverless-workgroup-data", 
    "EventBusName": "default", 
    "Targets": [ 
        {
            "Id": "2",
            "Arn": "arn:aws:redshift-serverless:us-east-1:123456789012:workgroup/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "RoleArn": "arn:aws:iam::123456789012:role/Administrator", 
            "RedshiftDataParameters": {
                "Database": "dev",
                "Sql": "select 1;",
                "StatementName": "test-redshift-serverless-workgroup-data", 
                "WithEvent": true 
            } 
        } 
    ] 
}
```

## 使用多個 SQL 陳述式和叢集進行呼叫
<a name="data-api-calling-event-bridge-sqls-cluster"></a>

下列範例使用 AWS CLI 建立 EventBridge 規則，用於對 Amazon Redshift 叢集執行多個 SQL 陳述式。

```
aws events put-rule 
--name  test-redshift-cluster-data 
--schedule-expression "rate(1 minute)"
```

然後，會建立 EventBridge 目標以便依照規則中指定的排程來執行。

```
aws events put-targets 
--cli-input-json file://data.json
```

data.json 輸入檔案如下。`Sqls` JSON 索引鍵表示有多個 SQL 陳述式。`Arn` JSON 值包含叢集識別碼。`RoleArn` JSON 值包含用來執行 SQL 的 IAM 角色，如先前所述。

```
{
    "Rule": "test-redshift-cluster-data", 
    "EventBusName": "default", 
    "Targets": [ 
        {
            "Id": "2",
            "Arn": "arn:aws:redshift:us-east-1:123456789012:cluster:mycluster",
            "RoleArn": "arn:aws:iam::123456789012:role/Administrator", 
            "RedshiftDataParameters": {
                "Database": "dev",
                "Sqls": ["select 1;", "select 2;", "select 3;"],
                "StatementName": "test-redshift-cluster-data", 
                "WithEvent": true 
            } 
        } 
    ] 
}
```

## 使用多個 SQL 陳述式和工作群組進行呼叫
<a name="data-api-calling-event-bridge-sqls-workgroup"></a>

下列範例使用 AWS CLI 建立 EventBridge 規則，用於對 Amazon Redshift Serverless 工作群組執行多個 SQL 陳述式。

```
aws events put-rule 
--name  test-redshift-serverless-workgroup-data 
--schedule-expression "rate(1 minute)"
```

然後，會建立 EventBridge 目標以便依照規則中指定的排程來執行。

```
aws events put-targets 
--cli-input-json file://data.json
```

data.json 輸入檔案如下。`Sqls` JSON 索引鍵表示有多個 SQL 陳述式。`Arn` JSON 值包含工作群組名稱。`RoleArn` JSON 值包含用來執行 SQL 的 IAM 角色，如先前所述。

```
{
    "Rule": "test-redshift-serverless-workgroup-data", 
    "EventBusName": "default", 
    "Targets": [ 
        {
            "Id": "2",
            "Arn": "arn:aws:redshift-serverless:us-east-1:123456789012:workgroup/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "RoleArn": "arn:aws:iam::123456789012:role/Administrator", 
            "RedshiftDataParameters": {
                "Database": "dev",
                "Sqls": ["select 1;", "select 2;", "select 3;"],
                "StatementName": "test-redshift-serverless-workgroup-data", 
                "WithEvent": true 
            } 
        } 
    ] 
}
```

# 監控資料 API
<a name="data-api-monitoring"></a>

監控是維護資料 API 和其他 AWS 解決方案的可靠性、可用性和效能的重要部分。 AWS 提供下列監控工具來監看資料 API、在發生錯誤時回報，以及適時採取自動動作：
+ Amazon EventBridge 可用來自動化您的 AWS 服務，並自動回應系統事件，例如應用程式可用性問題或資源變更。來自 AWS 服務的事件會以近乎即時的方式交付至 EventBridge。您可編寫簡單的規則，來指示您在意的事件，以及當事件符合規則時所要自動執行的動作。如需詳細資訊，請參閱[「Amazon EventBridge 使用者指南」](https://docs.aws.amazon.com/eventbridge/latest/userguide/)。
+ AWS CloudTrail 會擷取由您的帳戶或代表 AWS 您的帳戶發出的 API 呼叫和相關事件，並將日誌檔案交付至您指定的 Amazon S3 儲存貯體。您可以識別呼叫的使用者和帳戶 AWS、進行呼叫的來源 IP 地址，以及呼叫的時間。若要進一步了解 Amazon Redshift 如何與 整合 AWS CloudTrail，請參閱[使用 CloudTrail 記錄](https://docs.aws.amazon.com/redshift/latest/mgmt/logging-with-cloudtrail.html)。如需 CloudTrail 的相關資訊，請參閱《[AWS CloudTrail 使用者指南](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/)》。

**Topics**
+ [在 Amazon EventBridge 中監控 Amazon Redshift 資料 API 的事件](data-api-monitoring-events.md)

# 在 Amazon EventBridge 中監控 Amazon Redshift 資料 API 的事件
<a name="data-api-monitoring-events"></a>

EventBridge 會從您自己的應用程式、軟體即服務 (SaaS) 應用程式和 AWS 服務提供即時資料串流，因此您可以在 EventBridge 中監控資料 API 事件。EventBridge 會將該資料路由到目標，例如 AWS Lambda 和 Amazon SNS。這些事件與 CloudWatch Events 中出現的事件相同，可提供近乎即時的系統事件串流，說明 AWS 資源的變更。事件會傳送至包含 Amazon Redshift 資料庫的帳戶。例如，如果您在另一個帳戶中擔任某個角色，事件便會傳送至該帳戶。如需詳細資訊，請參閱《Amazon EventBridge 使用者指南》**中的 [Amazon EventBridge 事件](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-events.html)。

當 `ExecuteStatement` 或 `BatchExecuteStatement` API 操作將 `WithEvent` 選項設定為 `true` 時，系統就會傳送資料 API 事件。事件的 `state` 欄位會包含下列其中一個值：
+ 已中止 — 使用者已停止執行查詢。
+ 失敗 — 查詢執行失敗。
+ 已完成 — 查詢已執行完成。

系統保證會提供事件。如需詳細資訊，請參閱《*Amazon EventBridge 使用者指南*》中的[來自 AWS 服務的事件](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-service-event.html)。

## 資料 API 的已完成事件範例
<a name="data-api-monitoring-events-finished"></a>

下列範例顯示當 `ExecuteStatement` API 操作完成時的資料 API 事件。在此範例中，名為 `test.testtable` 的陳述式已執行完成。

```
{
    "version": "0",
    "id": "18e7079c-dd4b-dd64-caf9-e2a31640dab0",
    "detail-type": "Redshift Data Statement Status Change",
    "source": "aws.redshift-data",
    "account": "123456789012",
    "time": "2020-10-01T21:14:26Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:redshift:us-east-1:123456789012:cluster:redshift-cluster-1"
    ],
    "detail": {
        "principal": "arn:aws:iam::123456789012:user/myuser",
        "statementName": "test.testtable",
        "statementId": "dd2e1ec9-2ee3-49a0-819f-905fa7d75a4a",
        "redshiftQueryId": -1,
        "state": "FINISHED",
        "rows": 1,
        "expireAt": 1601673265
    }
}
```

# AWS KMS 搭配 Amazon Redshift 資料 API 使用
<a name="data-api-kms"></a>

當您使用客戶受管金鑰加密 Amazon Redshift 叢集或 Redshift Serverless 工作群組時，Amazon Redshift Data API 會使用相同的客戶受管金鑰來存放和加密您的查詢和結果。

資料 API 預設會加密您的資料，以保護敏感資訊，例如查詢文字和查詢結果。它會針對此保護使用 擁有 AWS 的 AWS KMS 加密金鑰。

當您保護敏感資料時，靜態資料的預設加密可減少操作開銷和複雜性。此方法可協助您建置符合嚴格加密合規和法規要求的安全應用程式。

## 在 中使用授予 AWS KMS
<a name="data-api-kms-grants"></a>

資料 API 需要授予才能使用客戶受管金鑰。

當您`BatchExecuteStatement`針對使用客戶受管金鑰加密的叢集呼叫 `ExecuteStatement`或 時，Amazon Redshift 會透過傳送[https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateGrant.html](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateGrant.html)請求至 來代表您建立授予 AWS KMS。 AWS KMS 使用授予來授予資料 API 存取您帳戶中的 KMS 金鑰。

資料 API 需要授予 ，才能將客戶受管金鑰用於下列操作：
+ 傳送[https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html)請求至 AWS KMS ，以使用客戶受管金鑰加密查詢中繼資料。
+ 傳送[https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)請求至 AWS KMS ，以產生由客戶受管金鑰加密的資料金鑰。
+ 將[https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html)請求傳送至 AWS KMS 以解密加密的資料金鑰，以便他們可以加密您的資料。

您可以隨時撤銷授予的存取權，或移除客戶受管金鑰的 Amazon Redshift 存取權。如果您這麼做，資料 API 就無法再存取客戶受管金鑰加密的資料，這會影響依賴該資料的操作。例如，如果您在撤銷授予後嘗試擷取查詢結果或追蹤查詢狀態，資料 API 會傳回 `AccessDeniedException`。

## 客戶受管金鑰的金鑰政策
<a name="data-api-kms-policy"></a>

金鑰政策會控制客戶受管金鑰的存取權限。每個客戶受管金鑰都必須只有一個金鑰政策，其中包含決定誰可以使用金鑰及其使用方式的陳述式。在建立客戶受管金鑰時，可以指定金鑰政策。如需更多資訊，請參閱 *AWS Key Management Service 開發人員指南*中的[客戶受管金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#customer-mgn-key)。

若要搭配資料 API 使用客戶受管金鑰，您必須先允許存取 Amazon Redshift。金鑰政策中必須允許下列 API 操作：
+ `kms:CreateGrant`：新增客戶受管金鑰的授權。授予控制對指定 AWS KMS 金鑰的存取，允許存取 Amazon Redshift 所需的授予操作。如需詳細資訊，請參閱[在 中使用授予 AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)。

以下是金鑰政策範例：

```
"Statement":[
   {
      "Sid":"Allow access to principals authorized to use Amazon Redshift",
      "Effect":"Allow",
      "Principal":{
         "AWS":"*"
      },
      "Action":[
         "kms:DescribeKey",
         "kms:CreateGrant"
      ],
      "Resource":"*",
      "Condition":{
         "StringEquals":{
            "kms:ViaService":"redshift.amazonaws.com",
            "kms:CallerAccount":"111122223333"
         }
      }
   },
   {
      "Sid":"AllowKeyAdministratorsAccess",
      "Effect":"Allow",
      "Principal":{
         "AWS":"arn:aws:iam::111122223333:role/ExampleAdminRole"
      },
      "Action":"kms:*",
      "Resource":"*"
   },
   {
      "Sid":"AllowKeyUseForExampleRole",
      "Effect":"Allow",
      "Principal":{
         "AWS":"arn:aws:iam::111122223333:role/ExampleUserRole"
      },
      "Action":[
         "kms:Encrypt",
         "kms:Decrypt",
         "kms:ReEncrypt*",
         "kms:GenerateDataKey*",
         "kms:DescribeKey"
      ],
      "Resource":"*"
   }
]
```

## 資料 API 加密內容
<a name="data-api-kms-encryption"></a>

加密內容是選用的一組金鑰/值對，其中包含有關資料的其他內容資訊。 AWS KMS 會使用加密內容作為額外的已驗證資料，以支援已驗證的加密。當您在加密資料的請求中包含加密內容時， 會將加密內容 AWS KMS 繫結至加密的資料。若要解密資料，您必須在請求中包含相同的加密內容。

資料 API 在所有已佈建叢集 AWS KMS 的密碼編譯操作中使用相同的三個加密內容金鑰/值對：
+ `aws:redshift:arn` – 叢集的 Amazon Resource Name (ARN)
+ `aws:redshift:createtime` – 您請求建立叢集時的時間戳記
+ `serviceName` – `RedshiftDataAPI`

```
"EncryptionContextSubset": {
    "aws:redshift:arn": "arn:aws:redshift:us-east-1:123456789012:cluster:redshift-cluster",
    "aws:redshift:createtime": "20250815T0000Z",
    "serviceName": "RedshiftDataAPI",
}
```

資料 API 在所有 AWS KMS 無伺服器工作群組的密碼編譯操作中使用兩個加密內容金鑰/值對：
+ `aws:redshift-serverless:arn` – 命名空間的 Amazon Resource Name (ARN)
+ `serviceName` – RedshiftDataAPI

```
"EncryptionContextSubset": {
    "aws:redshift-serverless:arn": "arn:aws:redshift-serverless:us-east-1:123456789012:namespace:12345678-1234-1234-1234-123456789012",
    "serviceName": "RedshiftDataAPI"
}
```

如需加密的詳細資訊，請參閱 [的密碼編譯詳細資訊簡介 AWS KMS](https://docs.aws.amazon.com/kms/latest/cryptographic-details/intro.html)。如需 Amazon Redshift 和 AWS KMS 整合的詳細資訊，請參閱 [Amazon Redshift 如何使用 AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/services-redshift.html)。