

# 查询编辑器：将 JupyterLab 与 Aurora DSQL 结合使用
<a name="SECTION_program-with-jupyter"></a>

 本指南提供了有关如何将 JupyterLab 与 Python 结合使用以连接并查询 Amazon Aurora DSQL 的分步操作说明。JupyterLab 是一类常用的交互式计算环境，可在单个文档中整合代码、文本和可视化内容，被广泛用于数据科学与研究应用场景。

 以下说明将介绍在本地安装的 JupyterLab 与使用 Amazon SageMaker AI（一项完全托管的机器学习服务，可提供带数据工作流 UI 的托管环境）这两种场景中，Aurora DSQL 的基本用法。

## 开始使用
<a name="SECTION_program-with-jupyter-getting-started"></a>

### 要求
<a name="SECTION_program-with-jupyter-requirements"></a>
+  一个 Aurora DSQL 集群 
+  已配置的 AWS 凭证（仅限本地安装） 
+  Python 版本 3.9 或更高版本（仅限本地安装） 

### 使用本地 JupyterLab
<a name="SECTION_program-with-jupyter-local"></a>

 要开始使用 JupyterLab，用户必须先使用 Python 的 **pip** 安装该应用程序：

```
pip install jupyterlab
```

 随后，可以通过运行 **jupyter lab** 来打开 JupyterLab。这将在 localhost:8888 打开 JupyterLab 应用程序，可通过浏览器进行访问。继续操作之前，请确保已在本地环境中配置 AWS 凭证。

### 使用 Amazon SageMaker AI
<a name="SECTION_program-with-jupyter-sagemaker"></a>

 在 AWS 管理控制台中，转至 Amazon SageMaker AI 控制台页面，然后转至**应用程序和 IDE** 下的**笔记本**部分。您可以在此部分中选择**创建笔记本实例**以开始创建 SageMaker 环境。在单击**创建笔记本实例**之前，请选择实例类型和平台。

 有关设置和实例选项的更多信息，请参阅 [Amazon SageMaker AI 设置文档](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-setup-working-env.html)。

**注意**  
警告：使用 Amazon SageMaker AI 可能会导致您的 AWS 账户产生费用。

 在 SageMaker 实例变为活动状态后，您可以在**笔记本实例**部分中使用**打开 JupyterLab** 将其打开。在笔记本中开始使用 Aurora DSQL 之前，您必须以 SageMaker 实例的 IAM 角色身份提供对 DSQL 集群的访问权限。要执行此操作，最简单的方法是单击笔记本实例页面中的 IAM 角色的链接。您可以在该处编辑附加到 SageMaker IAM 角色的策略。有关配置 IAM 策略以允许访问 Aurora DSQL 的更多信息，请参阅[身份验证和授权](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/authentication-authorization.html)。

### 使用 JupyterLab 连接到 Aurora DSQL
<a name="SECTION_program-with-jupyter-connecting"></a>

 设置 JupyterLab 实例后，用于在本地环境和 SageMaker AI 中连接到 Aurora DSQL 的步骤相同。创建一个空白 Python 3 笔记本，可在其中添加带 Python 代码的单元。

 在 Python 单元中，从官方信任存储下载 Amazon 根证书：

```
import urllib.request
urllib.request.urlretrieve('https://www.amazontrust.com/repository/AmazonRootCA1.pem', 'root.pem')
```

 要连接到 Aurora DSQL，请先在 Python 单元中安装[适用于 Python 的 Aurora DSQL 连接器](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector)和 Psycopg 驱动程序，然后将其导入：

```
pip install aurora_dsql_python_connector psycopg
```

```
import aurora_dsql_psycopg as dsql
```

 导入该连接器后，您可以创建 DSQL 配置并进行连接。Aurora DSQL Python 连接器会在每次建立连接时自动创建身份验证令牌。

```
config = {
    'host': "your-cluster.dsql.us-east-1.on.aws",
    'region': "us-east-1",
    'user': "admin"
    }

conn = dsql.connect(**config)
```

 运行代码后，您现在应已建立与 Aurora DSQL 的 Psycopg 连接。随后，您可以使用 Psycopg 游标并提供您的 SQL 查询来运行查询。有关如何将 Psycopg 用于兼容 Postgres 的数据库的更多信息，请参阅 [Psycopg 文档](https://www.psycopg.org/psycopg3/docs/)。此查询的结果将以元组列表的形式存储在 `results_list` 中。

```
with conn:
    with conn.cursor() as cur:
        cur.execute("SELECT * FROM table")
        results_list = cur.fetchall()
```

 随后，您可以使用 Python 框架（如 [Pandas](https://pandas.pydata.org/)）来分析或可视化您的查询结果，例如：

```
pip install pandas

import pandas as pd

df = pd.DataFrame(tuples_list)
print(df)
print(f"Total records: {len(df)}")
```

## 示例笔记本
<a name="SECTION_program-with-jupyter-example"></a>

 [Aurora DSQL 示例存储库包含使用 Aurora DSQL 的示例笔记本。](https://github.com/aws-samples/aurora-dsql-samples/tree/main/python/jupyter/sample.ipynb)

## 延伸阅读
<a name="SECTION_program-with-jupyter-reading"></a>

 [Amazon SageMaker AI 设置文档](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-setup-working-env.html) 

 [适用于 Python 的 Aurora DSQL 连接器](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector) 

 [Pandas 文档](https://pandas.pydata.org/docs/user_guide/index.html) 