### Install sqlanydb via Command Line Source: https://github.com/sqlanywhere/sqlanydb/blob/master/README.rst Commands to install the sqlanydb package using either setup.py or pip. These commands should be run with administrative privileges. ```bash python setup.py install ``` ```bash pip install sqlanydb ``` -------------------------------- ### Execute SQL Queries with Parameters in Python using sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Illustrates how to execute SQL queries with parameters using the sqlanydb library in Python. It covers using qmark (?) style placeholders for single queries with `execute()` and efficient batch operations with `executemany()`. The example includes selecting data with a parameter and inserting multiple rows. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Execute with positional parameters (qmark style) cursor.execute( "SELECT * FROM Employees WHERE DepartmentID = ?", (100,) ) employees = cursor.fetchall() # Insert a single row with parameters cursor.execute( "INSERT INTO Products (Name, Price, Quantity) VALUES (?, ?, ?)", ('Widget', 29.99, 100) ) # Execute many - efficient batch insert products = [ ('Gadget', 49.99, 50), ('Gizmo', 19.99, 200), ('Doohickey', 9.99, 500) ] cursor.executemany( "INSERT INTO Products (Name, Price, Quantity) VALUES (?, ?, ?)", products ) # Check rows affected print(f"Rows inserted: {cursor.rowcount}") conn.commit() cursor.close() conn.close() ``` -------------------------------- ### Register Custom Data Type Converter Source: https://github.com/sqlanywhere/sqlanydb/blob/master/README.rst Example of registering a callback function to convert database types to Python objects. In this case, it converts decimal types to Python Decimal objects. ```python import decimal def decimal_callback(valueToConvert): return decimal.Decimal(valueToConvert) sqlanydb.register_converter(sqlanydb.DT_DECIMAL, decimal_callback) ``` -------------------------------- ### Fetch Query Results using Python sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Details the methods provided by the sqlanydb Cursor object for retrieving query results in Python. It covers `fetchone()` for a single row, `fetchmany(size)` for a specified number of rows, and `fetchall()` for all remaining rows. The example also demonstrates efficient iteration over results using a generator. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() cursor.execute("SELECT EmployeeID, GivenName, Surname FROM Employees") # Fetch one row at a time row = cursor.fetchone() print(row) # Output: (102, 'Fran', 'Whitney') # Fetch multiple rows (default arraysize is 1) cursor.arraysize = 5 # Set default fetch size rows = cursor.fetchmany() # Fetches 5 rows rows = cursor.fetchmany(10) # Fetches 10 rows # Fetch all remaining rows all_rows = cursor.fetchall() # Iterate through results efficiently using generator cursor.execute("SELECT * FROM Products") for row in cursor.rows(): print(row) cursor.close() conn.close() ``` -------------------------------- ### Cancel Long-Running Queries with sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt This example shows how to interrupt a SQL query that is taking too long to execute using the `cancel()` method on a sqlanydb connection. A separate thread is used to initiate the cancellation after a specified delay, demonstrating asynchronous query management. ```python import sqlanydb import threading import time conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') def cancel_after_delay(connection, delay): time.sleep(delay) connection.cancel() print("Query cancelled") # Start cancellation in background thread cancel_thread = threading.Thread(target=cancel_after_delay, args=(conn, 5)) cancel_thread.start() cursor = conn.cursor() try: # This long-running query will be cancelled after 5 seconds cursor.execute("SELECT * FROM VeryLargeTable WHERE complex_condition = 1") except sqlanydb.OperationalError as e: print(f"Query interrupted: {e.errortext}") cancel_thread.join() cursor.close() conn.close() ``` -------------------------------- ### Connect and Execute Query in SQL Anywhere Source: https://github.com/sqlanywhere/sqlanydb/blob/master/README.rst Demonstrates establishing a connection to a SQL Anywhere database, creating a cursor, executing a simple select statement, and closing the connection. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo' ) curs = conn.cursor() curs.execute("select 'Hello, world!'") print( "SQL Anywhere says: %s" % curs.fetchone() ) curs.close() conn.close() ``` -------------------------------- ### Working with Binary Data Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Illustrates how to insert and retrieve binary data, such as images, using the `Binary` class for BLOB columns. ```APIDOC ## Working with Binary Data The `Binary` class wraps binary data for insertion into BLOB columns. Binary data is retrieved as Python bytes objects. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Insert binary data using Binary wrapper image_data = open('photo.jpg', 'rb').read() cursor.execute( "INSERT INTO Documents (name, content) VALUES (?, ?)", ('photo.jpg', sqlanydb.Binary(image_data)) ) ``` -------------------------------- ### Connect to SQL Anywhere Database using Python Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Demonstrates various ways to establish a connection to a SQL Anywhere database using the sqlanydb library. It includes basic connection with credentials, alternative keyword usage, and using a context manager for automatic transaction handling. Connections should be closed after use. ```python import sqlanydb # Basic connection with user credentials and database conn = sqlanydb.connect( uid='dba', # User ID pwd='sql', # Password eng='demo', # Engine/server name dbn='demo' # Database name ) # Alternative connection using userid/password keywords conn = sqlanydb.connect( userid='DBA', password='mypassword', dbf='test' # Database file path (auto-starts engine) ) # Connection with context manager for automatic transaction handling with sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') as cursor: cursor.execute("SELECT * FROM Employees") results = cursor.fetchall() # Auto-commits on success, rolls back on exception # Always close connection when done conn.close() ``` -------------------------------- ### Retrieve Binary Data Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Demonstrates how to fetch binary content from a database table and save it to a local file. ```APIDOC ## SELECT /Documents ### Description Retrieves binary data (e.g., images) from the Documents table by name. ### Method GET ### Parameters #### Query Parameters - **name** (string) - Required - The name of the document to retrieve. ### Request Example SELECT content FROM Documents WHERE name = 'photo.jpg' ### Response #### Success Response (200) - **data** (bytes) - The binary content of the requested document. ``` -------------------------------- ### Python: Working with Binary Data using sqlanydb.Binary Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Demonstrates how to insert and retrieve binary data (like BLOBs) using the sqlanydb.Binary class in Python. Binary data is wrapped for insertion and retrieved as Python bytes objects. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Insert binary data using Binary wrapper image_data = open('photo.jpg', 'rb').read() cursor.execute( "INSERT INTO Documents (name, content) VALUES (?, ?)", ('photo.jpg', sqlanydb.Binary(image_data)) ) ``` -------------------------------- ### Retrieve and Save Binary Data with sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt This snippet demonstrates how to fetch binary data (e.g., images) from a SQL Anywhere database using sqlanydb and save it to a local file. It involves executing a SELECT query, fetching the result as a bytes object, and writing it to a file in binary write mode. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Retrieve binary data cursor.execute("SELECT content FROM Documents WHERE name = ?", ('photo.jpg',)) row = cursor.fetchone() retrieved_data = row[0] # Returns bytes object # Save to file with open('retrieved_photo.jpg', 'wb') as f: f.write(retrieved_data) conn.commit() cursor.close() conn.close() ``` -------------------------------- ### Python: Calling Stored Procedures with sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Illustrates how to execute stored procedures using the callproc() method in Python with sqlanydb. It covers handling parameters, fetching results, and managing multiple result sets. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Call a stored procedure with parameters # Equivalent to: CALL GetEmployeeCount(100) result = cursor.callproc('GetEmployeeCount', (100,)) # Fetch results if procedure returns a result set if cursor.description: rows = cursor.fetchall() print(rows) # Handle multiple result sets from a procedure cursor.callproc('MultiResultProcedure', ()) while True: if cursor.description: print("Result set:", cursor.fetchall()) if not cursor.nextset(): break conn.commit() cursor.close() conn.close() ``` -------------------------------- ### Python: Transaction Management with sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Demonstrates how to manage database transactions using commit() and rollback() methods in Python with sqlanydb. It also shows how to use a context manager for automatic transaction handling. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() try: # Perform multiple operations in a transaction cursor.execute("UPDATE Accounts SET balance = balance - 100 WHERE id = ?", (1,)) cursor.execute("UPDATE Accounts SET balance = balance + 100 WHERE id = ?", (2,)) # Commit the transaction conn.commit() print("Transfer completed successfully") except sqlanydb.DatabaseError as e: # Rollback on error conn.rollback() print(f"Transfer failed: {e.errortext}, Code: {e.errorcode}") # Using context manager for automatic commit/rollback with conn: # Creates cursor automatically cursor = conn.cursor() cursor.execute("INSERT INTO Logs (message) VALUES (?)", ('Operation completed',)) # Auto-commits if no exception, auto-rolls back on exception cursor.close() conn.close() ``` -------------------------------- ### Calling Stored Procedures Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Explains how to execute stored procedures using the `callproc()` method, including handling parameters and multiple result sets. ```APIDOC ## Calling Stored Procedures The `callproc()` method executes a stored procedure with the given parameters and returns the modified parameters (useful for OUT parameters). ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Call a stored procedure with parameters # Equivalent to: CALL GetEmployeeCount(100) result = cursor.callproc('GetEmployeeCount', (100,)) # Fetch results if procedure returns a result set if cursor.description: rows = cursor.fetchall() print(rows) # Handle multiple result sets from a procedure cursor.callproc('MultiResultProcedure', ()) while True: if cursor.description: print("Result set:", cursor.fetchall()) if not cursor.nextset(): break conn.commit() cursor.close() conn.close() ``` ``` -------------------------------- ### Handle Date and Time Values with sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt This code illustrates how to create and insert date, time, and timestamp values using sqlanydb's helper functions. It shows creating values directly and from Unix timestamps, then inserting them into a database table. Proper connection management is included. ```python import sqlanydb import time conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() # Create date/time values using helper functions date_val = sqlanydb.Date(2024, 12, 25) # '2024/12/25' time_val = sqlanydb.Time(14, 30, 0) # '14:30:00' timestamp_val = sqlanydb.Timestamp(2024, 12, 25, 14, 30, 0) # '2024/12/25 14:30:00' # Create from Unix timestamps current_ticks = time.time() today = sqlanydb.DateFromTicks(current_ticks) now_time = sqlanydb.TimeFromTicks(current_ticks) now_timestamp = sqlanydb.TimestampFromTicks(current_ticks) # Insert date/time values cursor.execute( "INSERT INTO Events (event_date, event_time, created_at) VALUES (?, ?, ?)", (date_val, time_val, timestamp_val) ) conn.commit() cursor.close() conn.close() ``` -------------------------------- ### Transaction Management Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Demonstrates how to manage database transactions using commit() and rollback() methods, including the use of context managers for automatic transaction handling. ```APIDOC ## Transaction Management The Connection object provides `commit()` and `rollback()` methods for transaction control. By default, auto-commit is disabled, so changes must be explicitly committed. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() try: # Perform multiple operations in a transaction cursor.execute("UPDATE Accounts SET balance = balance - 100 WHERE id = ?", (1,)) cursor.execute("UPDATE Accounts SET balance = balance + 100 WHERE id = ?", (2,)) # Commit the transaction conn.commit() print("Transfer completed successfully") except sqlanydb.DatabaseError as e: # Rollback on error conn.rollback() print(f"Transfer failed: {e.errortext}, Code: {e.errorcode}") # Using context manager for automatic commit/rollback with conn: # Creates cursor automatically cursor = conn.cursor() cursor.execute("INSERT INTO Logs (message) VALUES (?)", ('Operation completed',)) # Auto-commits if no exception, auto-rolls back on exception cursor.close() conn.close() ``` ``` -------------------------------- ### Date and Time Handling Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Helper functions for creating and inserting date, time, and timestamp values into the database. ```APIDOC ## POST /Events ### Description Inserts event records with specific date and time values using sqlanydb helper functions. ### Method POST ### Parameters #### Request Body - **event_date** (Date) - Required - Date of the event. - **event_time** (Time) - Required - Time of the event. - **created_at** (Timestamp) - Required - Timestamp of creation. ### Request Example INSERT INTO Events (event_date, event_time, created_at) VALUES ('2024/12/25', '14:30:00', '2024/12/25 14:30:00') ``` -------------------------------- ### Python: Registering Custom Type Converters with sqlanydb Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Shows how to register custom type converters using sqlanydb.register_converter() to map database types to specific Python objects, such as converting DECIMAL to Decimal and TIMESTAMP to datetime. ```python import sqlanydb import decimal from datetime import datetime # Convert DECIMAL types to Python Decimal objects def decimal_callback(value): return decimal.Decimal(value) sqlanydb.register_converter(sqlanydb.DT_DECIMAL, decimal_callback) # Convert TIMESTAMP to custom format def timestamp_callback(value): if value: return datetime.strptime(value, '%Y/%m/%d %H:%M:%S') return None sqlanydb.register_converter(sqlanydb.DT_TIMESTAMP, timestamp_callback) # Now query results will use the converters conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() cursor.execute("SELECT price FROM Products") # DECIMAL column row = cursor.fetchone() print(type(row[0])) # Output: cursor.execute("SELECT created_at FROM Orders") # TIMESTAMP column row = cursor.fetchone() print(type(row[0])) # Output: cursor.close() conn.close() ``` -------------------------------- ### Registering Type Converters Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Shows how to register custom type converters using `register_converter()` to map database types to specific Python objects. ```APIDOC ## Registering Type Converters The `register_converter()` function allows custom conversion of database types to Python objects. Register a callback function for any supported data type constant. ```python import sqlanydb import decimal from datetime import datetime # Convert DECIMAL types to Python Decimal objects def decimal_callback(value): return decimal.Decimal(value) sqlanydb.register_converter(sqlanydb.DT_DECIMAL, decimal_callback) # Convert TIMESTAMP to custom format def timestamp_callback(value): if value: return datetime.strptime(value, '%Y/%m/%d %H:%M:%S') return None sqlanydb.register_converter(sqlanydb.DT_TIMESTAMP, timestamp_callback) # Now query results will use the converters conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() cursor.execute("SELECT price FROM Products") # DECIMAL column row = cursor.fetchone() print(type(row[0])) # Output: cursor.execute("SELECT created_at FROM Orders") # TIMESTAMP column row = cursor.fetchone() print(type(row[0])) # Output: cursor.close() conn.close() ``` ``` -------------------------------- ### Create and Use Cursors for Database Operations in Python Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Explains how to create and utilize Cursor objects with the sqlanydb Python library. Cursors are essential for executing SQL statements and fetching data. The snippet shows creating a cursor, executing a simple query, fetching a single result, and inspecting cursor description for metadata. Cursors and connections must be closed. ```python import sqlanydb conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') # Create a cursor cursor = conn.cursor() # Execute a simple query cursor.execute("SELECT 'Hello, world!'") result = cursor.fetchone() print(result) # Output: ('Hello, world!',) # Check cursor description for column metadata cursor.execute("SELECT EmployeeID, GivenName, Surname FROM Employees") print(cursor.description) # Output: (('EmployeeID', NUMBER, None, 4, 11, 0, 0), # ('GivenName', STRING, None, 20, 0, 0, 1), ...) # Close cursor and connection cursor.close() conn.close() ``` -------------------------------- ### Error Handling Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Details the exception hierarchy provided by sqlanydb and how to catch specific database errors, including accessing error text and codes. ```APIDOC ## Error Handling sqlanydb provides a hierarchy of exception classes following the DB-API 2.0 specification. All exceptions include `errortext` and `errorcode` properties for detailed error information. ```python import sqlanydb try: conn = sqlanydb.connect(uid='dba', pwd='wrong_password', eng='demo', dbn='demo') except sqlanydb.OperationalError as e: print(f"Connection failed: {e.errortext}") print(f"Error code: {e.errorcode}") conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() try: cursor.execute("SELECT * FROM NonExistentTable") except sqlanydb.ProgrammingError as e: print(f"SQL error: {e.errortext}, Code: {e.errorcode}") try: cursor.execute("INSERT INTO Employees (EmployeeID) VALUES (?)", (1,)) except sqlanydb.IntegrityError as e: print(f"Constraint violation: {e.errortext}") # Exception hierarchy: # sqlanydb.Error (base) # ├── sqlanydb.InterfaceError (client-side errors) # └── sqlanydb.DatabaseError (server-side errors) # ├── sqlanydb.DataError # ├── sqlanydb.OperationalError # ├── sqlanydb.IntegrityError # ├── sqlanydb.InternalError # ├── sqlanydb.ProgrammingError # └── sqlanydb.NotSupportedError cursor.close() conn.close() ``` ``` -------------------------------- ### Explore sqlanydb Module-Level Constants Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt This snippet demonstrates accessing various module-level constants provided by sqlanydb. These constants define the library's DB-API 2.0 compliance level, thread safety, parameter placeholder style, and version information, along with type objects for data comparisons. ```python import sqlanydb # DB-API 2.0 compliance level print(sqlanydb.apilevel) # Output: '2.0' # Thread safety level (1 = module-level thread safety) print(sqlanydb.threadsafety) # Output: 1 # Parameter placeholder style print(sqlanydb.paramstyle) # Output: 'qmark' (uses ? placeholders) # Package version print(sqlanydb.__version__) # Output: '1.0.14' # Type objects for comparison print(sqlanydb.STRING) # DBAPISet for string types print(sqlanydb.BINARY) # DBAPISet for binary types print(sqlanydb.NUMBER) # DBAPISet for numeric types print(sqlanydb.DATETIME) # DBAPISet for datetime types print(sqlanydb.DATE) # DBAPISet for date types print(sqlanydb.TIME) # DBAPISet for time types ``` -------------------------------- ### Python: Error Handling with sqlanydb Exceptions Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Explains how to handle database errors in Python using sqlanydb's exception hierarchy, which follows DB-API 2.0. It demonstrates catching specific errors like OperationalError, ProgrammingError, and IntegrityError, and accessing error details. ```python import sqlanydb try: conn = sqlanydb.connect(uid='dba', pwd='wrong_password', eng='demo', dbn='demo') except sqlanydb.OperationalError as e: print(f"Connection failed: {e.errortext}") print(f"Error code: {e.errorcode}") conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo') cursor = conn.cursor() try: cursor.execute("SELECT * FROM NonExistentTable") except sqlanydb.ProgrammingError as e: print(f"SQL error: {e.errortext}, Code: {e.errorcode}") try: cursor.execute("INSERT INTO Employees (EmployeeID) VALUES (?)", (1,)) except sqlanydb.IntegrityError as e: print(f"Constraint violation: {e.errortext}") # Exception hierarchy: # sqlanydb.Error (base) # ├── sqlanydb.InterfaceError (client-side errors) # └── sqlanydb.DatabaseError (server-side errors) # ├── sqlanydb.DataError # ├── sqlanydb.OperationalError # ├── sqlanydb.IntegrityError # ├── sqlanydb.InternalError # ├── sqlanydb.ProgrammingError # └── sqlanydb.NotSupportedError cursor.close() conn.close() ``` -------------------------------- ### Cancel Long-Running Queries Source: https://context7.com/sqlanywhere/sqlanydb/llms.txt Explains how to use the connection.cancel() method to interrupt queries from a separate thread. ```APIDOC ## POST /cancel ### Description Interrupts a long-running query execution on the current connection. ### Method POST ### Parameters - None ### Response #### Success Response (200) - **status** (string) - Confirmation that the query was interrupted. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.