Help Center/ AI DataLake/ SDK Reference/ Engine-specific SDKs/ Python SDKs/ Spark SDK (Python)/ Connecting to the Database and Querying Data Using Spark
Updated on 2026-11-06 GMT+08:00

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

Functions

cursor
# 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

Table 1 Parameter description

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