

 从补丁 198 开始，Amazon Redshift 将不再支持创建新的 Python UDF。现有的 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 Python 连接器
<a name="python-redshift-driver"></a>

通过使用适用于 Python 的 Amazon Redshift 连接器，您可以将工作与[适用于 Python 的 AWS SDK（Boto3）](https://github.com/boto/boto3)以及 Pandas 和 Numerical Python（NumPy）集成。有关 pandas 的更多信息，请参阅 [pandas GitHub 存储库](https://github.com/pandas-dev/pandas)。有关 NumPy 的更多信息，请参阅 [NumPy GitHub 存储库](https://github.com/numpy/numpy)。

Amazon Redshift Python 连接器提供了一个开源解决方案。您可以浏览源代码、请求增强功能、报告问题和提供文章。

要使用 Amazon Redshift Python 连接器，请确保使用 Python 3.6 或更高版本。有关更多信息，请参阅[Amazon Redshift Python 驱动程序许可协议](https://github.com/aws/amazon-redshift-python-driver/blob/master/LICENSE)。

Amazon Redshift Python 连接器提供以下内容：
+ AWS Identity and Access Management（IAM）身份验证 有关更多信息，请参阅 [Amazon Redshift 中的 Identity and Access Management](redshift-iam-authentication-access-control.md)。
+ 使用联合 API 访问进行身份提供者身份验证 企业身份提供者支持联合 API 访问，如下所示：
  + Azure AD 有关更多信息，请参阅 AWS 大数据博客文章 [Federate Amazon Redshift access with Microsoft Azure AD single sign-on](https://aws.amazon.com/blogs/big-data/federate-amazon-redshift-access-with-microsoft-azure-ad-single-sign-on/)。
  + Active Directory 联合身份验证服务 有关更多信息，请参阅 AWS 大数据博客文章 [Federate access to your Amazon Redshift cluster with Active Directory Federation Services (AD FS): Part 1](https://aws.amazon.com/blogs/big-data/federate-access-to-your-amazon-redshift-cluster-with-active-directory-federation-services-ad-fs-part-1/)。
  + Okta。有关更多信息，有关更多信息，请参阅 AWS 大数据博客文章 [Federate Amazon Redshift access with Okta as an identity provider](https://aws.amazon.com/blogs/big-data/federate-amazon-redshift-access-with-okta-as-an-identity-provider/)。
  + PingFederate。有关更多信息，请参阅 [PingFederate 站点](https://www.pingidentity.com/en/software/pingfederate.html)。
  + JumpCloud。有关的更多信息，请参阅 [JumpCloud 站点](https://jumpcloud.com/)。
+ Amazon Redshift 数据类型。

Amazon Redshift Python 连接器实施 Python 数据库 API 规范 2.0。有关更多信息，请参阅 Python 网站上的 [PEP 249 – Python 数据库 API 规范 v2.0](https://www.python.org/dev/peps/pep-0249/)。

**Topics**
+ [安装 Amazon Redshift Python 连接器](python-driver-install.md)
+ [Amazon Redshift Python 连接器的配置选项](python-configuration-options.md)
+ [导入 Python 连接器](python-start-import.md)
+ [将 Python 连接器与 NumPy 集成](python-connect-integrate-numpy.md)
+ [将 Python 连接器与 pandas 集成](python-connect-integrate-pandas.md)
+ [使用身份提供者插件](python-connect-identity-provider-plugins.md)
+ [使用 Amazon Redshift Python 连接器的示例](python-connect-examples.md)
+ [Amazon Redshift Python 连接器的 API 参考](python-api-reference.md)

# 安装 Amazon Redshift Python 连接器
<a name="python-driver-install"></a>

您可以使用以下任意一种方法安装 Amazon Redshift Python 连接器：
+ Python 包索引（PyPI）
+ Conda
+ 克隆 GitHub 存储库

## 从 PyPI 安装 Python 连接器
<a name="python-pip-install-pypi"></a>

要从 Python 包索引（PyPI）安装 Python 连接器，您可以使用 pip。要执行此操作，请运行以下命令。

```
>>> pip install redshift_connector
```

您可以在虚拟环境中安装连接器。要执行此操作，请运行以下命令。

```
>>> pip install redshift_connector
```

或者，你可以用连接器安装 pandas 和 NumPy。

```
>>> pip install 'redshift_connector[full]'
```

有关 pip 的更多信息，请参阅 [pip 站点](https://pip.pypa.io/en/stable/)。

## 从 Conda 安装 Python 连接器
<a name="python-pip-install-from-conda"></a>

你可以从 Anaconda.org 安装 Python 连接器。

```
>>>conda install -c conda-forge redshift_connector
```

## 通过从 AWS 中克隆 GitHub 存储库来安装 Python 连接器
<a name="python-pip-install-from-source"></a>

要从源代码安装 Python 连接器，请从 AWS 克隆 GitHub 存储库。安装 Python 和 virtualenv 之后，通过运行以下命令来设置环境并安装所需的依赖项。

```
$ git clone https://github.com/aws/amazon-redshift-python-driver.git
$ cd amazon-redshift-python-driver
$ virtualenv venv
$ . venv/bin/activate
$ python -m pip install -r requirements.txt
$ python -m pip install -e .
$ python -m pip install redshift_connector
```

# Amazon Redshift Python 连接器的配置选项
<a name="python-configuration-options"></a>

下面，您可以找到您可以为 Amazon Redshift Python 连接器指定的选项的说明。除非另有说明，否则以下选项适用于最新的可用连接器版本。

## access\$1key\$1id
<a name="python-access-key-id-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

为 IAM 数据库身份验证配置的 IAM 角色或用户的访问密钥 ID。

此参数为可选的。

## allow\$1db\$1user\$1override
<a name="python-allow-db-user-override-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

True  
指定连接器使用安全断言标记语言（SAML）断言中的 `DbUser` 值。

False  
指定使用 `DbUser` 连接参数中的值。

此参数为可选的。

## app\$1name
<a name="python-app-name-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

用于身份验证的身份提供者（IdP）应用程序的名称。

此参数为可选的。

## application\$1name
<a name="python-application_name-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

传递给 Amazon Redshift 以供审计的客户端应用程序的名称。您提供的应用程序名称显示在 [SYS\$1CONNECTION\$1LOG](https://docs.aws.amazon.com/redshift/latest/dg/SYS_CONNECTION_LOG.html) 表的“application\$1name”列中。这有助于在调试问题时跟踪连接源并对其进行故障排除。

此参数为可选的。

## auth\$1profile
<a name="python-auth-profile-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

连接属性为 JSON 的 Amazon Redshift 身份验证配置文件的名称。有关命名连接参数的更多信息，请参阅 `RedshiftProperty` 类。`RedshiftProperty` 类存储由最终用户提供的连接参数，如果适用，在 IAM 身份验证过程中生成（例如，临时 IAM 凭证）。有关更多信息，请参阅 [RedshiftProperty 类](https://github.com/aws/amazon-redshift-python-driver/blob/master/redshift_connector/redshift_property.py#L9)。

此参数为可选项。

## auto\$1create
<a name="python-auto-create-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

一个值，指示在用户不存在的情况下是否创建用户。

此参数为可选的。

## client\$1id
<a name="python-client-id-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Azure IdP 中的客户端 ID。

此参数为可选的。

## client\$1secret
<a name="python-client-secret-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Azure IdP 中的客户端密钥。

此参数为可选的。

## cluster\$1identifier
<a name="python-cluster-identifier-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Amazon Redshift 集群的集群标识符。

此参数为可选的。

## credentials\$1provider
<a name="python-credential-provider-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

对 Amazon Redshift 进行身份验证的 IdP。有效值如下所示：
+ `AdfsCredentialsProvider`
+ `AzureCredentialsProvider`
+ `BrowserAzureCredentialsProvider`
+ `BrowserAzureOAuth2CredentialsProvider`
+ `BrowserIdcAuthPlugin` – 使用 AWS IAM Identity Center 的授权插件。
+ `BrowserSamlCredentialsProvider`
+ `IdpTokenAuthPlugin` – 一种授权插件，可接受 AWS IAM Identity Center 令牌，或者基于 OpenID Connect（OIDC）JSON 的身份令牌（JWT），该令牌由与 AWS IAM Identity Center 关联的任意 Web 身份提供者提供。
+ `PingCredentialsProvider`
+ `OktaCredentialsProvider`

此参数为可选的。

## database
<a name="python-database-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

要连接到的数据库的名称。

此参数为必需参数。

## database\$1metadata\$1current\$1db\$1only
<a name="python-database-metadata-current-db-only-option"></a>
+ **默认值** – True
+ **数据类型** – Boolean

一个值，指示应用程序是否支持多数据库数据共享目录。默认值 True 表示应用程序不支持多数据库数据共享目录以实现向后兼容性。

此参数为可选的。

## db\$1groups
<a name="python-db-groups-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

DbUser 指示的用户为当前会话加入的现有数据库组名称的逗号分隔列表。

此参数为可选的。

## db\$1user
<a name="python-db-user-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

用于 Amazon Redshift 的用户 ID。

此参数为可选的。

## endpoint\$1url
<a name="python-endpoint-url-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Amazon Redshift 端点 URL。此选项仅供 AWS 内部使用。

此参数为可选的。

## group\$1federation
<a name="python-group-federation-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

此选项指定是否使用 Amazon Redshift IDP 组。

此参数为可选的。

**true**  
使用 Amazon Redshift 身份提供者 (IDP) 组。

**false**  
使用 STS API 和 GetClusterCredentials 进行用户联合身份验证，并指定用于连接的 **db\$1groups**。

## host
<a name="python-host-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Amazon Redshift 集群的主机名。

此参数为可选的。

## IAM
<a name="python-iam-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

IAM 身份验证已启用。

此参数为必需参数。

## iam\$1disable\$1cache
<a name="python-iam-disable-cache-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

此选项指定是否缓存 IAM 凭证。IAM 凭证将默认被缓存。当对 API 网关的请求受到限制时，这样可以提高性能。

此参数为可选的。

## idc\$1client\$1display\$1name
<a name="python-idc_client_display_name-option"></a>
+ **默认值** – Amazon Redshift Python 连接器
+ **数据类型** – 字符串

要用于使用 BrowserIdcAuthPlugin 的客户端的显示名称。

此参数为可选的。

## idc\$1region
<a name="python-idc_region"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

AWS IAM Identity Center 实例所在的 AWS 区域。

只有在 credentials\$1provider 配置选项中使用 `BrowserIdcAuthPlugin` 进行身份验证时，才需要此参数。

## idp\$1partition
<a name="python-idp_partition-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

指定在其中配置身份提供者（IdP）的云分区。这决定了驱动程序连接到哪个 IdP 身份验证端点。

如果将此参数留空，则驱动程序默认为商业分区。可能的值有：
+  `us-gov`：如果在 Azure Government 中配置了 IdP，请使用此值。例如，Azure AD Government 使用端点 `login.microsoftonline.us`。
+  `cn`：如果在中国云分区中配置了 IdP，请使用此值。例如，Azure AD China 使用 `login.chinacloudapi.cn` 端点。

此参数为可选的。

## idpPort
<a name="python-idp-port-option"></a>
+ **默认值** – 7890
+ **数据类型** – 整数

IdP 将 SAML 断言发送到的侦听端口。

此参数为必需参数。

## idp\$1response\$1timeout
<a name="python-idp-response-timeout-option"></a>
+ **默认值** – 120
+ **数据类型** – 整数

从 IdP 检索 SAML 断言的超时时间。

此参数为必需参数。

## idp\$1tenant
<a name="python-idp-tenant-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

IdP 租户。

此参数为可选的。

## issuer\$1url
<a name="python-issuer_url"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

 指向 AWS IAM Identity Center 服务器的实例端点。

只有在 credentials\$1provider 配置选项中使用 `BrowserIdcAuthPlugin` 进行身份验证时，才需要此参数。

## listen\$1port
<a name="python-listen-port-option"></a>
+ **默认值** – 7890
+ **数据类型** – 整数

通过浏览器插件使用 SAML、Azure AD 或 AWS IAM Identity Center 服务时，驱动程序用于接收来自身份提供者的 SAML 响应的端口。

此参数为可选的。

## login\$1url
<a name="python-login-url-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

IdP 的单点登录 Url。

此参数为可选的。

## max\$1prepared\$1statements
<a name="python-max-prepared-statements-option"></a>
+ **默认值**：1000
+ **数据类型** – 整数

每个连接将缓存的最大预处理语句数。将该参数设置为 0 将禁用缓存机制。为此参数输入负数会将其设置为默认值。

此参数为可选的。

## numeric\$1to\$1float
<a name="python-numeric-to-float-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

此选项指定连接器是否将数字数据类型值从 decimal.Decimal 转换为浮点数。默认情况下，连接器将数字数据类型值作为 decimal.Decimal 接收，而不会转换它们。

我们不建议为需要精确度的用例启用 numeric\$1to\$1float（数字转浮点），因为结果可能会四舍五入。

有关 decimal.Decimal 以及它与浮点数之间的权衡的更多信息，请参阅 Python 网站上的 [decimal — 十进制定点和浮点算术](https://docs.python.org/3/library/decimal.html)。

此参数为可选的。

## partner\$1sp\$1id
<a name="python-partner-sp-id-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

用于 Ping 身份验证的合作伙伴 SP ID。

此参数为可选的。

## password
<a name="python-password-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

用于身份验证的密码。

此参数为可选的。

## port
<a name="python-port-option"></a>
+ **默认值** – 5439
+ **数据类型** – 整数

Amazon Redshift 集群的端口号。

此参数为必需参数。

## preferred\$1role
<a name="python-preferred-role-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

当前连接首选的 IAM 角色。

此参数为可选的。

## principal\$1arn
<a name="python-principal-arn-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

要为其生成策略的用户或 IAM 角色的 Amazon 资源名称（ARN）。建议您将策略附加到角色，然后将该角色分配给用户以进行访问。

此参数为可选的。

## 配置文件
<a name="python-profile-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

包含 AWS 凭据的 AWS 凭据文件中的配置文件的名称。

此参数为可选的。

## provider\$1name
<a name="python-provider_name-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Redshift 本机验证提供程序的名称。

此参数为可选的。

## region
<a name="python-region-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

集群所在的 AWS 区域。

此参数为可选的。

## role\$1arn
<a name="python-role-arn-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

调用方承担的角色的 Amazon 资源名称（ARN）。此参数由 `JwtCredentialsProvider` 指示的提供程序使用。

对于 `JwtCredentialsProvider` 提供商，此参数为必填项。否则，此参数位可选项。

## role\$1session\$1name
<a name="python-role-session-name-option"></a>
+ **默认值** – jwt\$1redshift\$1session
+ **数据类型** – 字符串

所代入角色会话的标识符。通常，您可以传递与使用您的应用程序的用户关联的名称或标识符。您的应用程序使用的临时安全凭证与该用户相关联。此参数由 `JwtCredentialsProvider` 指示的提供程序使用。

此参数为可选的。

## 范围
<a name="python-scope-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

用户可以同意的范围列表，以空格分隔。您可以指定此参数，以便应用程序可以获得您想调用的 API 的同意。在为 credentials\$1provider 选项指定 BrowserAzureOAuth2CredentialsProvider 时，您可以指定此参数。

此参数是 BrowserAzureOAuth2CredentialsProvider 插件必需的。

## secret\$1access\$1key\$1id
<a name="python-secret-access-key-id-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

为 IAM 数据库身份验证配置的 IAM 角色或用户的秘密访问密钥。

此参数为可选的。

## session\$1token
<a name="python-session-token-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

为 IAM 数据库身份验证配置的 IAM 角色或用户的访问密钥 ID。如果使用临时 AWS 凭证，则需要此参数。

此参数为可选的。

## serverless\$1acct\$1id
<a name="python-serverless-acct-id-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Amazon Redshift Serverless 账户 ID。

此参数为可选的。

## serverless\$1work\$1group
<a name="python-serverless-work-group-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

Amazon Redshift Serverless 工作组名称。

此参数为可选的。

## ssl
<a name="python-ssl-option"></a>
+ **默认值** – True
+ **数据类型** – Boolean

已启用安全套接字层（SSL） 

此参数为必需参数。

## ssl\$1insecure
<a name="python-ssl-insecure-option"></a>
+ **默认值** – False
+ **数据类型** – Boolean

指定是否禁用 IdP 主机的服务器 SSL 证书验证的值。将此参数设置为 True，将禁用对 IdP 主机的服务器 SSL 证书的验证。我们建议您在生产环境中保持默认值 False。

此参数为可选的。

## sslmode
<a name="python-sslmode-option"></a>
+ **默认值** – verify-ca
+ **数据类型** – 字符串

与 Amazon Redshift 的连接的安全性。您可以指定以下任一值：
+ verify-ca
+ verify-full

此参数为必需参数。

## tcp\$1keepalive
<a name="python-tcp_keepalive-option"></a>
+ **默认值** – True
+ **数据类型** – Boolean

是否使用 TCP keepalive 来防止连接超时。可以指定以下值：
+ True：驱动程序将使用 TCP keepalive 来防止连接超时。
+ False：驱动程序不使用 TCP Keepalive。

此参数为可选的。

## tcp\$1keepalive\$1count
<a name="python-tcp_keepalive_count-option"></a>
+ **默认值** – 无
+ **数据类型** – 整数

所发送的未确认探测器的数量，超过此数量后将连接视为不活动。例如，将该值设置为 3 意味着，驱动程序在发送了 3 个未回应的 keepalive 数据包之后，就会确定连接不再处于活动状态。

如果未指定此参数，Amazon Redshift 将使用系统默认值。

此参数为可选的。

## tcp\$1keepalive\$1interval
<a name="python-tcp_keepalive_interval-option"></a>
+ **默认值** – 无
+ **数据类型** – 整数

驱动程序在未收到上一个探测器的确认时，发送后续 keepalive 探测器时的间隔（以秒为单位）。指定此参数时，必须使用正整数。

如果未指定此参数，Amazon Redshift 将使用系统默认值。

此参数为可选的。

## tcp\$1keepalive\$1idle
<a name="python-tcp_keepalive_idle-option"></a>
+ **默认值** – 无
+ **数据类型** – 整数

不活动的持续时间（以秒为单位），驱动程序将在此时间之后发送第一个 keepalive 探测器。例如，将该值设置为 120 意味着，对于不活动状态，驱动程序将会等待 2 分钟，然后发送第一个 keepalive 数据包。指定此参数时，必须使用正整数。

如果未指定此参数，Amazon Redshift 将使用系统默认值。

此参数为可选的。

## timeout
<a name="python-timeout-option"></a>
+ **默认值** – 无
+ **数据类型** – 整数

连接服务器时发生超时前等待的秒数。

此参数为可选的。

## 令牌
<a name="python-token-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

AWS IAM Identity Center 提供的访问令牌，或 OpenID Connect（OIDC）JSON Web 令牌（JWT，JSON Web Token），该令牌由与 AWS IAM Identity Center 关联的 Web 身份提供者提供。您的应用程序必须通过 AWS IAM Identity Center 或与 AWS IAM Identity Center 关联的身份提供者，对您的应用程序用户进行身份验证，从而生成此令牌。

此参数可用于 `IdpTokenAuthPlugin`。

## token\$1type
<a name="python-token_type-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

`IdpTokenAuthPlugin` 中使用的令牌类型。

可以指定以下值：

**ACCESS\$1TOKEN**  
如果您使用 AWS IAM Identity Center 提供的访问令牌，请输入此项。

**EXT\$1JWT**  
如果您使用 OpenID Connect（OIDC）JSON Web 令牌（JWT）（该令牌由与 AWS IAM Identity Center 集成的基于 Web 的身份提供者提供），请输入此项。

此参数可用于 `IdpTokenAuthPlugin`。

## 用户
<a name="python-user-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

用于身份验证的用户名。

此参数为可选的。

## web\$1identity\$1token
<a name="python-web-identity-token-option"></a>
+ **默认值** – 无
+ **数据类型** – 字符串

身份提供者提供的 OAuth 2.0 访问令牌或 OpenID Connect ID 令牌。通过使用 Web 身份提供者对使用您的应用程序的用户进行身份验证，确保您的应用程序获取此令牌。`JwtCredentialsProvider` 指示的提供商使用此参数。

对于 `JwtCredentialsProvider` 提供商，此参数为必填项。否则，此参数位可选项。

# 导入 Python 连接器
<a name="python-start-import"></a>

要导入 Python 连接器，请运行以下命令。

```
>>> import redshift_connector
```

要使用 AWS 凭证连接到 Amazon Redshift 集群，请运行以下命令。

```
conn = redshift_connector.connect(
    host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com',
    port=5439,
    database='dev',
    user='awsuser',
    password='my_password'
 )
```

# 将 Python 连接器与 NumPy 集成
<a name="python-connect-integrate-numpy"></a>

以下是将 Python 连接器与 NumPy 集成的示例。

```
>>>  import numpy
#Connect to the cluster
>>> import redshift_connector
>>> conn = redshift_connector.connect(
     host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com',
     port=5439,
     database='dev',
     user='awsuser',
     password='my_password'
  )
  
# Create a Cursor object
>>> cursor = conn.cursor()

# Query and receive result set            
cursor.execute("select * from book")

result: numpy.ndarray = cursor.fetch_numpy_array()
print(result)
```

以下是结果。

```
[['One Hundred Years of Solitude' 'Gabriel García Márquez']
['A Brief History of Time' 'Stephen Hawking']]
```

# 将 Python 连接器与 pandas 集成
<a name="python-connect-integrate-pandas"></a>

以下是将 Python 连接器与 pandas 集成的示例。

```
>>> import pandas

#Connect to the cluster
>>> import redshift_connector
>>> conn = redshift_connector.connect(
     host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com',
     port=5439,
     database='dev',
     user='awsuser',
     password='my_password'
  )
  
# Create a Cursor object
>>> cursor = conn.cursor()

# Query and receive result set
cursor.execute("select * from book")
result: pandas.DataFrame = cursor.fetch_dataframe()
print(result)
```

# 使用身份提供者插件
<a name="python-connect-identity-provider-plugins"></a>

有关如何使用身份提供者插件的一般信息，请参阅[用于提供 IAM 凭证的选项](options-for-providing-iam-credentials.md)。有关管理 IAM 身份的更多信息，包括 IAM 角色的最佳实践，请参阅 [Amazon Redshift 中的 Identity and Access Management](redshift-iam-authentication-access-control.md)。

## 使用 ADFS 身份提供者插件进行身份验证
<a name="python-connect-identity-provider-active-dir"></a>

以下是使用 Active Directory 联合身份验证服务（ADFS）身份提供者插件对连接到 Amazon Redshift 数据库的用户进行身份验证的示例。

```
>>> con = redshift_connector.connect(
    iam=True,
    database='dev',
    host='my-testing-cluster.abc.us-east-2.redshift.amazonaws.com',
    cluster_identifier='my-testing-cluster',
    credentials_provider='AdfsCredentialsProvider',
    user='brooke@myadfshostname.com',
    password='Hunter2',
    idp_host='myadfshostname.com'
)
```

## 使用 Azure 身份提供者插件进行身份验证
<a name="python-connect-identity-provider-azure"></a>

以下是使用 Azure 身份提供者插件进行身份验证的示例。您可以为 `client_id` 和 `client_secret` 创建值用于 Azure 企业应用程序，如下所示。

```
>>>  con = redshift_connector.connect(
    iam=True,
    database='dev',
    host='my-testing-cluster.abc.us-east-2.redshift.amazonaws.com',
    cluster_identifier='my-testing-cluster',
    credentials_provider='AzureCredentialsProvider',
    user='brooke@myazure.org',
    password='Hunter2',
    idp_tenant='my_idp_tenant',
    client_id='my_client_id',
    client_secret='my_client_secret',
    preferred_role='arn:aws:iam:123:role/DataScientist'
)
```

## 使用 AWS IAM Identity Center 身份提供者插件进行身份验证
<a name="python-connect-identity-provider-aws-idc"></a>

 以下是使用 AWS IAM Identity Center 身份提供者插件进行身份验证的示例。

```
with redshift_connector.connect(
credentials_provider='BrowserIdcAuthPlugin',
host='my-testing-cluster.abc.us-east-2.redshift.amazonaws.com',
database='dev',
idc_region='us-east-1',
issuer_url='https://identitycenter.amazonaws.com/ssoins-790723ebe09c86f9',
idp_response_timeout=60,
listen_port=8100,
idc_client_display_name='Test Display Name',
# port value of 5439 is specified by default
)
```

## 使用 Azure 浏览器身份提供者插件进行身份验证
<a name="python-connect-identity-provider-azure-browser"></a>

以下是使用 Azure 浏览器身份提供者插件对连接到 Amazon Redshift 数据库的用户进行身份验证的示例。

浏览器中会发生多重身份验证，其中登录凭证由用户提供。

```
>>>con = redshift_connector.connect(
    iam=True,
    database='dev',
    host='my-testing-cluster.abc.us-east-2.redshift.amazonaws.com',
    cluster_identifier='my-testing-cluster',
    credentials_provider='BrowserAzureCredentialsProvider',
    idp_tenant='my_idp_tenant',
    client_id='my_client_id',
)
```

## 使用 Okta 身份提供者插件进行身份验证
<a name="python-connect-identity-provider-okta"></a>

以下是使用 Okta 身份提供者插件进行身份验证的示例。你可以通过 Okta 应用程序获取 `idp_host`、`app_id` 和 `app_name` 的值。

```
>>> con = redshift_connector.connect(
    iam=True,
    database='dev',
    host='my-testing-cluster.abc.us-east-2.redshift.amazonaws.com',
    cluster_identifier='my-testing-cluster',
    credentials_provider='OktaCredentialsProvider',
    user='brooke@myazure.org',
    password='hunter2',
    idp_host='my_idp_host',
    app_id='my_first_appetizer',
    app_name='dinner_party'
)
```

## 使用 JumpCloud 和通用 SAML 浏览器身份提供者插件进行身份验证
<a name="python-connect-identity-provider-jumpcloud"></a>

以下是使用 JumpCloud 和通用 SAML 浏览器身份提供者插件进行身份验证的示例。

密码参数是必需的。但是，您不必输入此参数，因为浏览器中会发生多重验证。

```
>>> con = redshift_connector.connect(
    iam=True,
    database='dev',
    host='my-testing-cluster.abc.us-east-2.redshift.amazonaws.com',
    cluster_identifier='my-testing-cluster',
    credentials_provider='BrowserSamlCredentialsProvider',
    user='brooke@myjumpcloud.org',
    password='',
    login_url='https://sso.jumpcloud.com/saml2/plustwo_melody'
)
```

# 使用 Amazon Redshift Python 连接器的示例
<a name="python-connect-examples"></a>

以下为如何使用 Amazon Redshift Python 连接器的示例。要运行它们，您必须先安装 Python 连接器。有关安装 Amazon Redshift Python 连接器的更多信息，请参阅[安装 Amazon Redshift Python 连接器](python-driver-install.md)。有关可以与 Python 连接器一起使用的配置选项的更多信息，请参阅 [Amazon Redshift Python 连接器的配置选项](python-configuration-options.md)。

**Topics**
+ [使用 AWS 凭证连接到 Amazon Redshift 集群并进行查询](#python-connect-cluster)
+ [启用自动提交](#python-connect-enable-autocommit)
+ [配置游标参数样式](#python-connect-config-paramstyle)
+ [使用 COPY 从 Amazon S3 桶中复制数据，然后使用 UNLOAD 将数据写入该桶](#python-connect-copy-unload-s3)

## 使用 AWS 凭证连接到 Amazon Redshift 集群并进行查询
<a name="python-connect-cluster"></a>

下面的示例将指导您使用 AWS 凭证连接到 Amazon Redshift 集群，然后查询表并检索查询结果。

```
#Connect to the cluster
>>> import redshift_connector
>>> conn = redshift_connector.connect(
     host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com',
     database='dev',
     port=5439,
     user='awsuser',
     password='my_password'
  )
  
# Create a Cursor object
>>> cursor = conn.cursor()

# Query a table using the Cursor
>>> cursor.execute("select * from book")
                
#Retrieve the query result set
>>> result: tuple = cursor.fetchall()
>>> print(result)
 >> (['One Hundred Years of Solitude', 'Gabriel García Márquez'], ['A Brief History of Time', 'Stephen Hawking'])
```

## 启用自动提交
<a name="python-connect-enable-autocommit"></a>

根据 Python 数据库 API 规范，默认情况下自动提交属性处于关闭状态。在执行回滚命令后，您可以使用以下命令打开连接的 autocommit 属性，以确保事务不在进行中。

```
#Connect to the cluster
>>> import redshift_connector
>>> conn = redshift_connector.connect(...)

# Run a rollback command
>>>  conn.rollback()

# Turn on autocommit
>>>  conn.autocommit = True
>>>  conn.run("VACUUM")

# Turn off autocommit
>>>  conn.autocommit = False
```

## 配置游标参数样式
<a name="python-connect-config-paramstyle"></a>

可以通过 cursor.paramstyle 修改游标的参数样式。使用的原定设置参数样式是 `format`。参数样式的有效值为 `qmark`、`numeric`、`named`、`format` 和 `pyformat`。

以下是使用各种参数样式将参数传递给示例 SQL 语句的示例。

```
# qmark
redshift_connector.paramstyle = 'qmark'
sql = 'insert into foo(bar, jar) VALUES(?, ?)'
cursor.execute(sql, (1, "hello world"))

# numeric
redshift_connector.paramstyle = 'numeric'
sql = 'insert into foo(bar, jar) VALUES(:1, :2)'
cursor.execute(sql, (1, "hello world"))

# named
redshift_connector.paramstyle = 'named'
sql = 'insert into foo(bar, jar) VALUES(:p1, :p2)'
cursor.execute(sql, {"p1":1, "p2":"hello world"})

# format
redshift_connector.paramstyle = 'format'
sql = 'insert into foo(bar, jar) VALUES(%s, %s)'
cursor.execute(sql, (1, "hello world"))

# pyformat
redshift_connector.paramstyle = 'pyformat'
sql = 'insert into foo(bar, jar) VALUES(%(bar)s, %(jar)s)'
cursor.execute(sql, {"bar": 1, "jar": "hello world"})
```

## 使用 COPY 从 Amazon S3 桶中复制数据，然后使用 UNLOAD 将数据写入该桶
<a name="python-connect-copy-unload-s3"></a>

以下示例说明如何将数据从 Amazon S3 桶复制到表中，然后从该表卸载回到此桶中。

包含以下数据的名为 `category_csv.txt` 的文本文件将上载到 Amazon S3 桶中。

```
12,Shows,Musicals,Musical theatre
13,Shows,Plays,"All ""non-musical"" theatre"
14,Shows,Opera,"All opera, light, and ""rock"" opera"
15,Concerts,Classical,"All symphony, concerto, and choir concerts"
```

以下是 Python 代码的示例，该代码首先连接到 Amazon Redshift 数据库。然后创建一个名为 `category` 的表并将 S3 桶中的 CSV 数据复制到表中。

```
#Connect to the cluster and create a Cursor
>>> import redshift_connector
>>> with redshift_connector.connect(...) as conn:
>>> with conn.cursor() as cursor:

#Create an empty table
>>>     cursor.execute("create table category (catid int, cargroup varchar, catname varchar, catdesc varchar)")

#Use COPY to copy the contents of the S3 bucket into the empty table 
>>>     cursor.execute("copy category from 's3://testing/category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;")

#Retrieve the contents of the table
>>>     cursor.execute("select * from category")
>>>     print(cursor.fetchall())

#Use UNLOAD to copy the contents of the table into the S3 bucket
>>>     cursor.execute("unload ('select * from category') to 's3://testing/unloaded_category_csv.txt'  iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;")

#Retrieve the contents of the bucket
>>>     print(cursor.fetchall())
 >> ([12, 'Shows', 'Musicals', 'Musical theatre'], [13, 'Shows', 'Plays', 'All "non-musical" theatre'], [14, 'Shows', 'Opera', 'All opera, light, and "rock" opera'], [15, 'Concerts', 'Classical', 'All symphony, concerto, and choir concerts'])
```

如果您未将 `autocommit` 设置为 true，请在运行 `execute()` 语句后使用 `conn.commit()` 提交。

数据卸载到 S3 桶的 `unloaded_category_csv.text0000_part00` 文件中，内容如下：

```
12,Shows,Musicals,Musical theatre
13,Shows,Plays,"All ""non-musical"" theatre"
14,Shows,Opera,"All opera, light, and ""rock"" opera"
15,Concerts,Classical,"All symphony, concerto, and choir concerts"
```

# Amazon Redshift Python 连接器的 API 参考
<a name="python-api-reference"></a>

您可以在文中找到有关 Amazon Redshift Python 连接器 API 操作的说明。

## redshift\$1connector
<a name="python-api-redshift_connector"></a>

在下文中，您可以找到有关 `redshift_connector` API 操作的描述。

`connect(user, database, password[, port, …])`  
创建到 Amazon Redshift 集群的连接。此函数可验证用户输入，可以选择使用身份提供者插件进行身份验证，然后构造连接对象。

`apilevel`  
支持的 DBAPI 级别，目前为“2.0”。

`paramstyle``str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str`  
要在全局使用的数据库 API 参数样式。

## 连接
<a name="python-api-connection"></a>

您可以在文中找到有关 Amazon Redshift Python 连接器的连接 API 操作的说明。

`__init__(user, password, database[, host, …])`  
初始化原始连接对象。

`cursor`  
创建绑定到此连接的游标对象。

`commit`  
提交当前数据库事务。

`rollback`  
回滚当前的数据库事务。

`close`  
关闭数据库连接。

`execute(cursor, operation, vals)`  
运行指定的 SQL 命令。您可以将参数作为序列或映射提供，具体取决于 `redshift_connector.paramstyle` 的值。

`run(sql[, stream])`  
运行指定的 SQL 命令。或者，您也可以提供与 COPY 命令一起使用的流。

`xid(format_id, global_transaction_id, …)`  
创建事务 ID。postgres 中只使用了 `global_transaction_id` 参数。postgres 中不使用 format\$1id 和 branch\$1qualifier。`global_transaction_id` 可以是 postgres 支持的任何返回元组的字符串标识符（`format_id`、`global_transaction_id`、`branch_qualifier`）。

`tpc_begin(xid)`  
使用由格式 ID、全局事务 ID 和分支限定符组成的事务 ID `xid` 开始 TPC 事务。

`tpc_prepare`  
执行以 .tpc\$1begin 开始的事务的第一阶段。

`tpc_commit([xid])`  
在没有参数的情况下进行调用时，.tpc\$1commit 会提交之前使用 .tpc\$1prepare() 准备的 TPC 事务。

`tpc_rollback([xid])`  
在没有参数的情况下进行调用时，.tpc\$1rollback 会回滚 TPC 事务。

`tpc_recover`  
返回适合与 .tpc\$1commit(xid) 或 .tpc\$1rollback(xid) 一起使用的待处理事务 ID 列表。

## Cursor
<a name="python-api-cursor"></a>

在下文中，您可以找到有关 游标 API 操作的描述。

`__init__(connection[, paramstyle])`  
初始化原始游标对象。

`insert_data_bulk(filename, table_name, parameter_indices, column_names, delimiter, batch_size)`  
运行批量 INSERT 语句。

`execute(operation[, args, stream, …])`  
运行数据库操作。

`executemany(operation, param_sets)`  
准备数据库操作，然后为提供的所有参数序列或映射运行该操作。

`fetchone`  
获取查询结果集的下一行。

`fetchmany([num])`  
获取查询结果的下一个行集。

`fetchall`  
获取查询结果的所有剩余行。

`close`  
立即关闭光标。

`__iter__`  
可以迭代游标对象以从查询中检索行。

`fetch_dataframe([num])`  
返回最后查询结果的数据框。

`write_dataframe(df, table)`  
将相同的结构数据框写入 Amazon Redshift 数据库。

`fetch_numpy_array([num])`  
返回最后查询结果的 NumPy 数组。

`get_catalogs`  
Amazon Redshift 不支持来自单个连接的多个目录。Amazon Redshift 只返回当前目录。

`get_tables([catalog, schema_pattern, …])`  
返回系统中用户定义的唯一公共表。

`get_columns([catalog, schema_pattern, …])`  
返回 Amazon Redshift 数据库中特定表中所有列的列表。

## AdfsCredentialsProvider 插件
<a name="python-adfs-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 AdfsCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.AdfsCredentialsProvider()
```

## AzureCredentialsProvider 插件
<a name="python-azure-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 AzureCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.AzureCredentialsProvider()
```

## BrowserAzureCredentialsProvider 插件
<a name="python-browser-azure-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 BrowserAzureCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.BrowserAzureCredentialsProvider()
```

## BrowserSamlCredentialsProvider 插件
<a name="python-browser-saml-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 BrowserSamlCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.BrowserSamlCredentialsProvider()
```

## OktaCredentialsProvider 插件
<a name="python-okta-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 OktaCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.OktaCredentialsProvider()
```

## PingCredentialsProvider 插件
<a name="python-ping-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 PingCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.PingCredentialsProvider()
```

## SamlCredentialsProvider 插件
<a name="python-saml-credentials-plugin"></a>

以下是 Amazon Redshift Python 连接器的 SamlCredentialsProvider 插件 API 操作的语法。

```
redshift_connector.plugin.SamlCredentialsProvider()
```