|
2 | 2 | title: 使用 databend-sqlalchemy 集成 Databend Cloud |
3 | 3 | --- |
4 | 4 |
|
5 | | -在本教程中,我们将引导您了解如何使用 `databend-sqlalchemy` 库连接到 Databend Cloud,创建表,插入数据以及使用 Python 查询结果。 |
| 5 | +在本教程中,我们将引导你使用 `databend-sqlalchemy` 库连接 Databend Cloud,并通过 Python 创建表、插入数据及查询结果。 |
6 | 6 |
|
7 | | -## 准备工作 |
| 7 | +## 在开始之前 |
8 | 8 |
|
9 | | -在开始之前,请确保您已成功创建计算集群并获得了连接信息。有关如何执行此操作,请参见 [连接到计算集群](/guides/cloud/using-databend-cloud/warehouses#connecting)。 |
| 9 | +开始前,请确保已成功创建计算集群(Warehouse)并获取连接信息。具体操作请参阅[连接计算集群(Warehouse)](/guides/cloud/using-databend-cloud/warehouses#connecting)。 |
10 | 10 |
|
11 | | -## 步骤 1:使用 pip 安装依赖项 |
| 11 | +## 第一步:使用 pip 安装依赖项 |
12 | 12 |
|
13 | 13 | ```shell |
14 | 14 | pip install databend-sqlalchemy |
15 | 15 | ``` |
16 | 16 |
|
17 | | -## 步骤 2:使用 databend_sqlalchemy 连接 |
| 17 | +## 第二步:使用 databend_sqlalchemy 连接 |
18 | 18 |
|
19 | | -1. 复制以下代码并粘贴到文件 `main.py` 中: |
| 19 | +1. 复制以下代码至文件 `main.py`: |
20 | 20 |
|
21 | 21 | ```python |
22 | | -from databend_sqlalchemy import connector |
23 | | - |
24 | | -# 使用您的凭据连接到 Databend Cloud(替换 PASSWORD、HOST、DATABASE 和 WAREHOUSE_NAME) |
25 | | -cursor = connector.connect(f"databend://cloudapp:{PASSWORD}@{HOST}:443/{DATABASE}?warehouse={WAREHOUSE_NAME}").cursor() |
26 | | -cursor.execute('DROP TABLE IF EXISTS data') |
27 | | -cursor.execute('CREATE TABLE IF NOT EXISTS data( Col1 TINYINT, Col2 VARCHAR )') |
28 | | -cursor.execute("INSERT INTO data (Col1, Col2) VALUES (%s, %s), (%s, %s)", [1, 'yy', 2, 'xx']) |
29 | | -cursor.execute("SELECT * FROM data") |
30 | | -print(cursor.fetchall()) |
| 22 | +from sqlalchemy import create_engine, text |
| 23 | +from sqlalchemy.engine.base import Connection, Engine |
| 24 | + |
| 25 | +# Connecting to Databend Cloud with your credentials (replace PASSWORD, HOST, DATABASE, and WAREHOUSE_NAME) |
| 26 | +engine = create_engine( |
| 27 | + f"databend://{username}:{password}@{host_port_name}/{database_name}?sslmode=disable" |
| 28 | +) |
| 29 | +cursor = engine.connect() |
| 30 | +cursor.execute(text('DROP TABLE IF EXISTS data')) |
| 31 | +cursor.execute(text('CREATE TABLE IF NOT EXISTS data( Col1 TINYINT, Col2 VARCHAR )')) |
| 32 | +cursor.execute(text("INSERT INTO data VALUES (1,'zz')")) |
| 33 | +res = cursor.execute(text("SELECT * FROM data")) |
| 34 | +print(res.fetchall()) |
31 | 35 | ``` |
32 | 36 |
|
33 | 37 | 2. 运行 `python main.py`: |
34 | 38 |
|
35 | 39 | ```bash |
36 | 40 | python main.py |
37 | | -[(1, 'yy'), (2, 'xx')] |
| 41 | +[(1, 'zz')] |
38 | 42 | ``` |
0 commit comments