Connecting to the Database and Querying Data Using Spark
Description
This section describes how to use AI DataLake DB-API to connect to a database and query data.
Prerequisites
- The Python SDK environment has been configured and initialized. For details, see Obtaining and Initializing the Spark SDK.
- Permissions related to APIs and SQL jobs have been configured. For details, see Permissions and Supported Actions.
- The compute resources and endpoints in use are available.
Functions
# Synchronous submission function execute(); # Function for retrieving SQL query results fetchall();
Sample Code
- Creating a connection
conn = connect( region="your_region", project_id="your_project_id", workspace_id="your_workspace_id", ak="your_access_key", sk="your_secret_key", endpoint="aidatalake_endpoint", database="default", )
- Executing SQL statements
try: cursor = conn.cursor() cursor.execute("SELECT 1 AS value, 'hello' AS greeting") row = cursor.fetchone() logger.info("Row: %s", row) cursor.close()try: cursor = conn.cursor() cursor.execute( "SELECT * FROM demo_table WHERE id = ? AND name = ?", [42, "test"], ) rows = cursor.fetchall() logger.info("Fetched %d rows", len(rows)) cursor.close()cursor = conn.cursor() # Retrieve the query result. cursor.execute( "SELECT * FROM demo_table WHERE id = :id AND name = :name", {"id": 42, "name": "test"}, ) for row in cursor: logger.info("Row: %s", row) # List catalogs catalogs = conn.list_catalogs() logger.info("Catalogs: %s", catalogs) # List schemas (databases) schemas = conn.list_schemas(catalog="default") logger.info("Schemas in 'default': %s", schemas)
Parameters
| Parameter | Mandatory (Yes/No) | Default Value | Description |
|---|---|---|---|
| region | Yes | None | Region name. |
| project_id | Yes | None | Project ID. |
| ak | Yes | None | Access key ID. |
| sk | Yes | None | Secret key. |
| endpoint | Yes | None | URL of the AI DataLake. |
| database | No | None | Name of the LakeFormation database. |
| workspace_id | Yes | None | Workspace ID. |
| catalog | No | None | LakeFormation catalog name. |
| security_token | No | None | Used when a temporary credential is used. |
| obs_endpoint | No | None | OBS endpoint. If this parameter is not set, obs.{RegionName}.myhuaweicloud.com is used by default. |
| endpoint_name | No | None | AI DataLake endpoint. Example: fabric.{regionName}.myhuaweicloud.com |
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot