Skip to content

Commit 8634c1f

Browse files
committed
Update 01-python.md
1 parent 6c62951 commit 8634c1f

File tree

1 file changed

+5
-249
lines changed

1 file changed

+5
-249
lines changed

docs/en/developer/00-drivers/01-python.md

Lines changed: 5 additions & 249 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: Python
44

55
Databend offers the following Python packages enabling you to develop Python applications that interact with Databend:
66

7-
- [databend-driver (**Recommended**)](https://pypi.org/project/databend-driver/): A Python driver for Databend, providing both synchronous and asynchronous interfaces to interact with the Databend database, execute SQL queries, and handle data operations.
7+
- [databend-driver (**Recommended**)](https://pypi.org/project/databend-driver/): A Python driver for Databend, providing both synchronous and asynchronous interfaces to interact with Databend, execute SQL queries, and handle data operations.
88
- [databend-sqlalchemy](https://github.com/databendcloud/databend-sqlalchemy): Provides a SQL toolkit and [Object-Relational Mapping](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) to interface with the Databend database. [SQLAlchemy](https://www.sqlalchemy.org/) is a popular SQL toolkit and ORM for Python, and databend-SQLAlchemy is a dialect for SQLAlchemy that allows you to use SQLAlchemy to interact with Databend.
99

1010
Both packages require Python version 3.7 or higher. To check your Python version, run `python --version` in your command prompt. To install the latest `databend-driver` or `databend-sqlalchemy` package:
@@ -47,252 +47,8 @@ This table illustrates the correspondence between Databend semi-structured data
4747
| BITMAP | str |
4848
| GEOMETRY | str |
4949

50-
## Tutorial-1: Integrating with Self-Hosted Databend
50+
## Tutorials
5151

52-
Before you start, make sure you have successfully installed a local Databend. For detailed instructions, see [Local and Docker Deployments](/guides/deploy/deploy/non-production/deploying-local).
53-
54-
### Step 1. Prepare a SQL User Account
55-
56-
To connect your program to Databend and execute SQL operations, you must provide a SQL user account with appropriate privileges in your code. Create one in Databend if needed, and ensure that the SQL user has only the necessary privileges for security.
57-
58-
This tutorial uses a SQL user named 'user1' with password 'abc123' as an example. As the program will write data into Databend, the user needs ALL privileges. For how to manage SQL users and their privileges, see [User & Role](/sql/sql-commands/ddl/user/).
59-
60-
```sql
61-
CREATE USER user1 IDENTIFIED BY 'abc123';
62-
GRANT ALL on *.* TO user1;
63-
```
64-
65-
### Step 2. Write a Python Program
66-
67-
In this step, you'll create a simple Python program that communicates with Databend. The program will involve tasks such as creating a table, inserting data, and executing data queries.
68-
69-
import Tabs from '@theme/Tabs';
70-
import TabItem from '@theme/TabItem';
71-
72-
<Tabs groupId="python">
73-
<TabItem value="databend-driver" label="databend-driver">
74-
75-
1. Install databend-driver.
76-
77-
```shell
78-
pip install databend-driver
79-
```
80-
81-
2. Copy and paste the following code to the file `main.py`:
82-
83-
```python title='main.py'
84-
from databend_driver import BlockingDatabendClient
85-
86-
# Connecting to a local Databend with a SQL user named 'user1' and password 'abc123' as an example.
87-
client = BlockingDatabendClient('databend://user1:[email protected]:8000/?sslmode=disable')
88-
89-
# Create a cursor to interact with Databend
90-
cursor = client.cursor()
91-
92-
# Create database and use it
93-
cursor.execute("CREATE DATABASE IF NOT EXISTS bookstore")
94-
cursor.execute("USE bookstore")
95-
96-
# Create table
97-
cursor.execute("CREATE TABLE IF NOT EXISTS booklist(title VARCHAR, author VARCHAR, date VARCHAR)")
98-
99-
# Insert data into the table
100-
cursor.execute("INSERT INTO booklist VALUES('Readings in Database Systems', 'Michael Stonebraker', '2004')")
101-
102-
# Query data from the table
103-
cursor.execute("SELECT * FROM booklist")
104-
rows = cursor.fetchall()
105-
106-
# Print the results
107-
for row in rows:
108-
print(f"{row[0]} {row[1]} {row[2]}")
109-
110-
# Drop the table and database
111-
cursor.execute('DROP TABLE booklist')
112-
cursor.execute('DROP DATABASE bookstore')
113-
114-
# Close the cursor
115-
cursor.close()
116-
```
117-
118-
3. Run `python main.py`:
119-
120-
```bash
121-
python main.py
122-
Readings in Database Systems Michael Stonebraker 2004
123-
```
124-
125-
</TabItem>
126-
127-
<TabItem value="databend-sqlalchemy with Object" label="databend-sqlalchemy (Connector)">
128-
129-
You will use the databend-sqlalchemy library to create a connector instance and execute SQL queries using the cursor object.
130-
131-
1. Install databend-sqlalchemy.
132-
133-
```shell
134-
pip install databend-sqlalchemy
135-
```
136-
137-
2. Copy and paste the following code to the file `main.py`:
138-
139-
```python title='main.py'
140-
from databend_sqlalchemy import connector
141-
142-
# Connecting to a local Databend with a SQL user named 'user1' and password 'abc123' as an example.
143-
# Feel free to use your own values while maintaining the same format.
144-
conn = connector.connect(f"http://user1:[email protected]:8000").cursor()
145-
conn.execute("CREATE DATABASE IF NOT EXISTS bookstore")
146-
conn.execute("USE bookstore")
147-
conn.execute("CREATE TABLE IF NOT EXISTS booklist(title VARCHAR, author VARCHAR, date VARCHAR)")
148-
conn.execute("INSERT INTO booklist VALUES('Readings in Database Systems', 'Michael Stonebraker', '2004')")
149-
conn.execute('SELECT * FROM booklist')
150-
151-
results = conn.fetchall()
152-
for (title, author, date) in results:
153-
print("{} {} {}".format(title, author, date))
154-
conn.execute('drop table booklist')
155-
conn.execute('drop database bookstore')
156-
157-
# Close Connect.
158-
conn.close()
159-
```
160-
161-
3. Run `python main.py`:
162-
163-
```text
164-
Readings in Database Systems Michael Stonebraker 2004
165-
```
166-
167-
</TabItem>
168-
169-
<TabItem value="databend-sqlalchemy with Engine" label="databend-sqlalchemy (Engine)">
170-
171-
You will use the databend-sqlalchemy library to create an engine instance and execute SQL queries using the connect method to create connections that can execute queries.
172-
173-
1. Install databend-sqlalchemy.
174-
175-
```shell
176-
pip install databend-sqlalchemy
177-
```
178-
179-
2. Copy and paste the following code to the file `main.py`:
180-
181-
```python title='main.py'
182-
from sqlalchemy import create_engine, text
183-
184-
# Connecting to a local Databend with a SQL user named 'user1' and password 'abc123' as an example.
185-
# Feel free to use your own values while maintaining the same format.
186-
# Setting secure=False means the client will connect to Databend using HTTP instead of HTTPS.
187-
engine = create_engine("databend://user1:[email protected]:8000/default?secure=False")
188-
189-
connection1 = engine.connect()
190-
connection2 = engine.connect()
191-
192-
with connection1.begin() as trans:
193-
connection1.execute(text("CREATE DATABASE IF NOT EXISTS bookstore"))
194-
connection1.execute(text("USE bookstore"))
195-
connection1.execute(text("CREATE TABLE IF NOT EXISTS booklist(title VARCHAR, author VARCHAR, date VARCHAR)"))
196-
connection1.execute(text("INSERT INTO booklist VALUES('Readings in Database Systems', 'Michael Stonebraker', '2004')"))
197-
198-
result = connection2.execute(text("SELECT * FROM booklist"))
199-
results = result.fetchall()
200-
201-
for (title, author, date) in results:
202-
print("{} {} {}".format(title, author, date))
203-
204-
# Close Connect.
205-
connection1.close()
206-
connection2.close()
207-
engine.dispose()
208-
```
209-
210-
3. Run `python main.py`:
211-
212-
```text
213-
Readings in Database Systems Michael Stonebraker 2004
214-
```
215-
216-
</TabItem>
217-
</Tabs>
218-
219-
## Tutorial-2: Integrating with Databend Cloud using databend-driver
220-
221-
Before you start, make sure you have successfully created a warehouse and obtained the connection information. For how to do that, see [Connecting to a Warehouse](/guides/cloud/using-databend-cloud/warehouses#connecting).
222-
223-
### Step 1. Install Dependencies with pip
224-
225-
```shell
226-
pip install databend-driver
227-
```
228-
229-
### Step 2. Connect with databend-driver
230-
231-
1. Copy and paste the following code to the file `main.py`:
232-
233-
```python
234-
from databend_driver import BlockingDatabendClient
235-
236-
# Connecting to Databend Cloud with your credentials (replace PASSWORD, HOST, DATABASE, and WAREHOUSE_NAME)
237-
client = BlockingDatabendClient(f"databend://cloudapp:{PASSWORD}@{HOST}:443/{DATABASE}?warehouse={WAREHOUSE_NAME}")
238-
239-
# Get a cursor from the client to execute queries
240-
cursor = client.cursor()
241-
242-
# Drop the table if it exists
243-
cursor.execute('DROP TABLE IF EXISTS data')
244-
245-
# Create the table if it doesn't exist
246-
cursor.execute('CREATE TABLE IF NOT EXISTS data (x Int32, y String)')
247-
248-
# Describe the table
249-
cursor.execute('DESC data')
250-
251-
# Insert data into the table
252-
cursor.execute("INSERT INTO data (x, y) VALUES (1, 'yy'), (2, 'xx')")
253-
254-
# Select all data from the table
255-
cursor.execute('SELECT * FROM data')
256-
257-
# Fetch all rows from the result
258-
rows = cursor.fetchall()
259-
260-
# Print the result
261-
for row in rows:
262-
print(row.values())
263-
```
264-
265-
2. Run `python main.py`:
266-
267-
```bash
268-
python main.py
269-
(1, 'yy')
270-
(2, 'xx')
271-
```
272-
273-
## Tutorial-3: Integrating with Databend Cloud using databend-sqlalchemy
274-
275-
Before you start, make sure you have successfully created a warehouse and obtained the connection information. For how to do that, see [Connecting to a Warehouse](/guides/cloud/using-databend-cloud/warehouses#connecting).
276-
277-
### Step 1. Install Dependencies with pip
278-
279-
```shell
280-
pip install databend-sqlalchemy
281-
```
282-
283-
### Step 2. Connect with Databend SQLAlchemy
284-
285-
```python
286-
from databend_sqlalchemy import connector
287-
288-
cursor = connector.connect(f"databend://{USER}:{PASSWORD}@${HOST}:443/{DATABASE}?&warehouse={WAREHOUSE_NAME}).cursor()
289-
cursor.execute('DROP TABLE IF EXISTS data')
290-
cursor.execute('CREATE TABLE IF NOT EXISTS data( Col1 TINYINT, Col2 VARCHAR )')
291-
cursor.execute("INSERT INTO data (Col1,Col2) VALUES ", [1, 'yy', 2, 'xx'])
292-
cursor.execute("SELECT * FROM data")
293-
print(cursor.fetchall())
294-
```
295-
296-
:::tip
297-
Replace `{USER}, {PASSWORD}, {HOST}, {WAREHOUSE_NAME} and {DATABASE}` in the code with your connection information. For how to obtain the connection information, see [Connecting to a Warehouse](/guides/cloud/using-databend-cloud/warehouses#connecting).
298-
:::
52+
- [Integrating with Databend Cloud using databend-driver](/tutorials/programming/python/integrating-with-databend-cloud-using-databend-driver)
53+
- [Integrating with Databend Cloud using databend-sqlalchemy](/tutorials/programming/python/integrating-with-databend-cloud-using-databend-sqlalchemy)
54+
- [Integrating with Self-Hosted Databend](/tutorials/programming/python/integrating-with-self-hosted-databend)

0 commit comments

Comments
 (0)