YDB DBAPI
ydb-dbapi is a Python DBAPI 2.0 compliant driver for YDB, a distributed SQL database. It provides both synchronous and asynchronous interfaces for interacting with YDB. The library is actively developed, with frequent minor releases, typically on a monthly cadence, reflecting ongoing enhancements and bug fixes.
Warnings
- gotcha Failing to explicitly call `connection.commit()` after DML (INSERT, UPDATE, DELETE) or DDL (CREATE, ALTER) statements will result in an implicit `ROLLBACK` when the connection is closed. This is mandated by PEP 249 and can lead to lost data if not handled carefully.
- gotcha YDB is a distributed database and its underlying SDK handles retryable errors. Improper error handling, especially not retrying transient failures, can lead to production incidents and brittle applications. The `ydb` SDK (used by `ydb-dbapi`) has built-in retry mechanisms; understand and configure them or implement appropriate retry logic at the application level.
- gotcha PEP 249 deprecates passing a list of tuples to `cursor.execute()` for inserting multiple rows. For improved efficiency and clarity when performing multiple inserts, `cursor.executemany()` should be used instead.
- breaking As `ydb-dbapi` is currently in a 0.x.x version series, breaking changes may be introduced in minor releases (e.g., 0.1.x to 0.2.x) without adhering to strict semantic versioning. Users should review release notes carefully when upgrading between minor versions.
Install
-
pip install ydb-dbapi
Imports
- connect
import ydb_dbapi connection = ydb_dbapi.connect(...)
- async_connect
import ydb_dbapi async_connection = await ydb_dbapi.async_connect(...)
Quickstart
import os
import ydb_dbapi
# Configuration for YDB connection
# Replace with your YDB endpoint and database path or set as environment variables
YDB_ENDPOINT = os.environ.get("YDB_ENDPOINT", "grpc://localhost:2136")
YDB_DATABASE = os.environ.get("YDB_DATABASE", "/local")
connection = None
cursor = None
try:
# Establish a synchronous connection to YDB
connection = ydb_dbapi.connect(
host=YDB_ENDPOINT,
database=YDB_DATABASE
)
print("Successfully connected to YDB.")
# Create a cursor object
cursor = connection.cursor()
# Execute a simple DDL query (create table if not exists)
cursor.execute("""
CREATE TABLE IF NOT EXISTS my_table (
id Int64,
value Utf8,
PRIMARY KEY (id)
);
""")
print("Table 'my_table' ensured to exist.")
connection.commit() # DDL statements usually imply a commit, but explicit is good practice.
# Execute an UPSERT statement to insert/update data
cursor.execute("UPSERT INTO my_table (id, value) VALUES (1, 'Hello');")
cursor.execute("UPSERT INTO my_table (id, value) VALUES (2, 'YDB DBAPI');")
connection.commit() # Commit the transaction
print("Inserted data into 'my_table'.")
# Execute a SELECT statement
cursor.execute("SELECT id, value FROM my_table ORDER BY id;")
# Fetch all results
rows = cursor.fetchall()
print("Fetched data:")
for row in rows:
print(f" ID: {row[0]}, Value: {row[1]}")
except ydb_dbapi.Error as e:
print(f"An YDB DBAPI error occurred: {e}")
if connection:
connection.rollback() # Rollback on error
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
if cursor:
cursor.close()
if connection:
connection.close()
print("Connection closed.")