Python API Reference

Bases: `object`

**Syntax**

```
class chdb.state.sqlitelike.Connection(connection_string: str)
```

---

#### `close`[​](#chdb-session-session-close "Direct link to chdb-session-session-close")

Close the connection and cleanup resources.

This method closes the database connection and cleans up any associated
resources including active cursors. After calling this method, the
connection becomes invalid and can't be used for further operations.

**Syntax**

```
close() → None
```

Note

This method is idempotent - calling it multiple times is safe.

Warning

Any ongoing streaming queries will be cancelled when the connection
is closed. Ensure all important data is processed before closing.

**Examples**

```
>>> conn = connect("test.db")
>>> # Use connection for queries
>>> conn.query("CREATE TABLE test (id INT) ENGINE = Memory")
>>> # Close when done
>>> conn.close()
```

```
>>> # Using with context manager (automatic cleanup)
>>> with connect("test.db") as conn:
...     conn.query("SELECT 1")
...     # Connection automatically closed
```

---

#### `cursor`[​](#chdb-state-sqlitelike-connection-cursor "Direct link to chdb-state-sqlitelike-connection-cursor")

Create a [Cursor](#chdb-state-sqlitelike-cursor) object for executing queries.

This method creates a database cursor that provides the standard
DB-API 2.0 interface for executing queries and fetching results.
The cursor allows for fine-grained control over query execution
and result retrieval.

**Syntax**

```
cursor() → Cursor
```

**Returns**

|  |  |  |  |
| --- | --- | --- | --- |
| Return Type Description|  |  | | --- | --- | | `Cursor` A cursor object for database operations | | | |

Note

Creating a new cursor will replace any existing cursor associated
with this connection. Only one cursor per connection is supported.

**Examples**

```
>>> conn = connect(":memory:")
>>> cursor = conn.cursor()
>>> cursor.execute("CREATE TABLE test (id INT, name String) ENGINE = Memory")
>>> cursor.execute("INSERT INTO test VALUES (1, 'Alice')")
>>> cursor.execute("SELECT * FROM test")
>>> rows = cursor.fetchall()
>>> print(rows)
((1, 'Alice'),)
```

**See also**

- [`Cursor`](#chdb-state-sqlitelike-cursor) - Database cursor implementation

---

#### `query`[​](#chdb-state-sqlitelike-connection-query "Direct link to chdb-state-sqlitelike-connection-query")

Execute a SQL query and return the complete results.

This method executes a SQL query synchronously and returns the complete
result set. It supports various output formats and automatically applies
format-specific post-processing.

**Syntax**

```
query(query: str, format: str = 'CSV') → Any
```

**Parameters:**

|  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Parameter Type Default Description|  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | | `query` str *required* SQL query string to execute|  |  |  |  | | --- | --- | --- | --- | | `format` str `"CSV"` Output format for results. Supported formats: • `"CSV"` - Comma-separated values (string) • `"JSON"` - JSON format (string) • `"Arrow"` - Apache Arrow format (bytes) • `"Dataframe"` - Pandas DataFrame (requires pandas) • `"Arrowtable"` - PyArrow Table (requires pyarrow) | | | | | | | | | | | |

**Returns**

|  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Return Type Description|  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | | `str` For string formats (CSV, JSON)|  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | | `bytes` For Arrow format|  |  |  |  | | --- | --- | --- | --- | | `pandas.DataFrame` For dataframe format|  |  | | --- | --- | | `pyarrow.Table` For arrowtable format | | | | | | | | | |

**Raises**

|  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- |
| Exception Condition|  |  |  |  | | --- | --- | --- | --- | | `RuntimeError` If query execution fails|  |  | | --- | --- | | `ImportError` If required packages for format aren't installed | | | | | |

Warning

This method loads the entire result set into memory. For large
results, consider using [`send_query()`](#chdb-state-sqlitelike-connection-send_query) for streaming.

**Examples**

```
>>> conn = connect(":memory:")
>>>
>>> # Basic CSV query
>>> result = conn.query("SELECT 1 as num, 'hello' as text")
>>> print(result)
num,text
1,hello
```

```
>>> # DataFrame format
>>> df = conn.query("SELECT number FROM numbers(5)", "dataframe")
>>> print(df)
   number
0       0
1       1
2       2
3       3
4       4
```

**See also**

- [`send_query()`](#chdb-state-sqlitelike-connection-send_query) - For streaming query execution

---

#### `send_query`[​](#chdb-state-sqlitelike-connection-send_query "Direct link to chdb-state-sqlitelike-connection-send_query")

Execute a SQL query and return a streaming result iterator.

This method executes a SQL query and returns a StreamingResult object
that allows you to iterate over the results without loading everything
into memory at once. This is ideal for processing large result sets.

**Syntax**

```
send_query(query: str, format: str = 'CSV') → StreamingResult
```

**Parameters**

|  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Parameter Type Default Description|  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | | `query` str *required* SQL query string to execute|  |  |  |  | | --- | --- | --- | --- | | `format` str `"CSV"` Output format for results. Supported formats: • `"CSV"` - Comma-separated values • `"JSON"` - JSON format • `"Arrow"` - Apache Arrow format (enables record\_batch() method) • `"dataframe"` - Pandas DataFrame chunks • `"arrowtable"` - PyArrow Table chunks | | | | | | | | | | | |

**Returns**

|  |  |  |  |
| --- | --- | --- | --- |
| Return Type Description|  |  | | --- | --- | | `StreamingResult` A streaming iterator for query results that supports: • Iterator protocol (for loops) • Context manager protocol (with statements) • Manual fetching with fetch() method • PyArrow RecordBatch streaming (Arrow format only) | | | |

**Raises**

|  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- |
| Exception Condition|  |  |  |  | | --- | --- | --- | --- | | `RuntimeError` If query execution fails|  |  | | --- | --- | | `ImportError` If required packages for format aren't installed | | | | | |

Note

Only the “Arrow” format supports the `record_batch()` method on the returned StreamingResult.

**Examples**

```
>>> conn = connect(":memory:")
>>>
>>> # Basic streaming
>>> stream = conn.send_query("SELECT number FROM numbers(1000)")
>>> for chunk in stream:
...     print(f"Processing chunk: {len(chunk)} bytes")
```

```
>>> # Using context manager for cleanup
>>> with conn.send_query("SELECT * FROM large_table") as stream:
...     chunk = stream.fetch()
...     while chunk:
...         process_data(chunk)
...         chunk = stream.fetch()
```

```
>>> # Arrow format with RecordBatch streaming
>>> stream = conn.send_query("SELECT * FROM data", "Arrow")
>>> reader = stream.record_batch(rows_per_batch=10000)
>>> for batch in reader:
...     print(f"Batch shape: {batch.num_rows} x {batch.num_columns}")
```

**See also**

- [`query()`](#chdb-state-sqlitelike-connection-query) - For non-streaming query execution
- [`StreamingResult`](#chdb-state-sqlitelike-streamingresult) - Streaming result iterator

---

### **class** `chdb.state.sqlitelike.StreamingResult`[​](#chdb-state-sqlitelike-streamingresult "Direct link to chdb-state-sqlitelike-streamingresult")

Bases: `object`

Streaming result iterator for processing large query results.

This class provides an iterator interface for streaming query results without
loading the entire result set into memory. It supports various output formats
and provides methods for manual result fetching and PyArrow RecordBatch streaming.

```
class chdb.state.sqlitelike.StreamingResult
```

---

#### `fetch`[​](#streamingresult-fetch "Direct link to streamingresult-fetch")

Fetch the next chunk of streaming results.