|
| 1 | +""" |
| 2 | +chdb API Example - Demonstrating the Connection and Cursor interfaces |
| 3 | +This example shows common usage patterns with explanatory comments |
| 4 | +""" |
| 5 | + |
| 6 | +import chdb |
| 7 | +from datetime import datetime, date |
| 8 | + |
| 9 | +# 1. Creating a connection |
| 10 | +# The connect function supports several connection string formats: |
| 11 | +# - ":memory:" (in-memory database, default) |
| 12 | +# - "test.db" or "file:test.db" (relative path) |
| 13 | +# - "/path/to/test.db" or "file:/path/to/test.db" (absolute path) |
| 14 | +# - Connection strings can include query parameters: "file:test.db?param1=value1" |
| 15 | + |
| 16 | +# Create an in-memory connection |
| 17 | +conn = chdb.connect(":memory:") |
| 18 | +# Alternative: conn = chdb.connect("test.db") # file-based connection |
| 19 | + |
| 20 | +# 2. Working with cursors |
| 21 | +# Cursors allow executing SQL queries and fetching results |
| 22 | +cursor = conn.cursor() |
| 23 | + |
| 24 | +# 3. Execute a simple query with multiple data types |
| 25 | +cursor.execute(""" |
| 26 | + SELECT |
| 27 | + 42 as int_val, |
| 28 | + 3.14 as float_val, |
| 29 | + 'hello' as str_val, |
| 30 | + true as bool_val, |
| 31 | + NULL as null_val, |
| 32 | + toDateTime('2024-03-20 15:30:00') as datetime_val, |
| 33 | + toDate('2024-03-20') as date_val |
| 34 | +""") |
| 35 | + |
| 36 | +# 4. Fetch methods |
| 37 | +# 4.1. fetchone() - returns a single row as a tuple, or None if no more rows |
| 38 | +row = cursor.fetchone() |
| 39 | +print("Single row:", row) |
| 40 | +# Output example: (42, 3.14, 'hello', True, None, datetime(2024,3,20,15,30), date(2024,3,20)) |
| 41 | + |
| 42 | +# 4.2. Execute a query with multiple rows |
| 43 | +cursor.execute(""" |
| 44 | + SELECT number, toString(number) as str_val |
| 45 | + FROM system.numbers |
| 46 | + LIMIT 5 |
| 47 | +""") |
| 48 | + |
| 49 | +# fetchmany(size) - returns up to 'size' rows as a tuple of tuples |
| 50 | +batch = cursor.fetchmany(2) |
| 51 | +print("First 2 rows:", batch) |
| 52 | +# Output example: ((0, '0'), (1, '1')) |
| 53 | + |
| 54 | +# fetchall() - returns all remaining rows as a tuple of tuples |
| 55 | +remaining = cursor.fetchall() |
| 56 | +print("Remaining rows:", remaining) |
| 57 | +# Output example: ((2, '2'), (3, '3'), (4, '4')) |
| 58 | + |
| 59 | +# 5. Cursor as an iterator |
| 60 | +cursor.execute("SELECT number FROM system.numbers LIMIT 3") |
| 61 | +print("Iterating through cursor:") |
| 62 | +for row in cursor: |
| 63 | + print(f" Row: {row}") |
| 64 | +# Output: |
| 65 | +# Row: (0,) |
| 66 | +# Row: (1,) |
| 67 | +# Row: (2,) |
| 68 | + |
| 69 | +# 6. Get metadata about the result set |
| 70 | +cursor.execute(""" |
| 71 | + SELECT |
| 72 | + 42 as int_col, |
| 73 | + 'hello' as str_col, |
| 74 | + now() as time_col |
| 75 | +""") |
| 76 | + |
| 77 | +# 6.1. column_names() - get a list of column names |
| 78 | +col_names = cursor.column_names() |
| 79 | +print("Column names:", col_names) |
| 80 | +# Output example: ['int_col', 'str_col', 'time_col'] |
| 81 | + |
| 82 | +# 6.2. column_types() - get a list of column types |
| 83 | +col_types = cursor.column_types() |
| 84 | +print("Column types:", col_types) |
| 85 | +# Output example: ['UInt8', 'String', 'DateTime'] |
| 86 | + |
| 87 | +# 6.3. description - DB-API 2.0 compatible column descriptions |
| 88 | +# Format: list of 7-item tuples (name, type_code, display_size, internal_size, precision, scale, null_ok) |
| 89 | +# Only name and type_code are populated in this implementation |
| 90 | +desc = cursor.description |
| 91 | +print("Description:", desc) |
| 92 | +# Output example: [('int_col', 'UInt8', None, None, None, None, None), ...] |
| 93 | + |
| 94 | +# 7. Using the Connection.query() method for direct queries |
| 95 | +# This method returns results directly without needing to create a cursor |
| 96 | + |
| 97 | +# 7.1. Default format is CSV |
| 98 | +csv_result = conn.query("SELECT 1 as val, 'test' as name") |
| 99 | +print("CSV query result:", csv_result) |
| 100 | +# Returns data in CSV format as a string |
| 101 | + |
| 102 | +# 7.2. Using Arrow format to get a PyArrow table |
| 103 | +# Note: requires pyarrow to be installed |
| 104 | +arrow_result = conn.query("SELECT 1 as val, 'test' as name", format="Arrow") |
| 105 | +print("Arrow query result type:", type(arrow_result)) |
| 106 | +# Returns a PyArrow Table object |
| 107 | + |
| 108 | +# 7.3. Using DataFrame format to get a pandas DataFrame |
| 109 | +# Note: requires both pyarrow and pandas to be installed |
| 110 | +df_result = conn.query("SELECT 1 as val, 'test' as name", format="dataframe") |
| 111 | +print("DataFrame query result:\n", df_result) |
| 112 | +# Returns a pandas DataFrame |
| 113 | + |
| 114 | +# 8. Error handling |
| 115 | +try: |
| 116 | + cursor.execute("SELECT non_existent_column") |
| 117 | +except Exception as e: |
| 118 | + print("SQL Error:", e) |
| 119 | + |
| 120 | +# 9. Always close resources when done |
| 121 | +cursor.close() |
| 122 | +conn.close() |
0 commit comments