Firebird for SQLAlchemy

2.1 · active · verified Thu Apr 16

SQLAlchemy-Firebird is an external dialect for SQLAlchemy, enabling Python applications to connect and interact with Firebird relational database servers. It provides a DBAPI 2.0 compliant interface, supporting both the `firebird-driver` (recommended for Python 3.8+ and Firebird 3+) and `fdb` drivers (for Python < 3.8 / SQLAlchemy 1.4+ and Firebird 2.5/3.0+). The library is actively maintained, with its current version being 2.1, and saw its last stable release in January 2024.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a Firebird database using SQLAlchemy-Firebird and the `create_engine` function. It utilizes environment variables for database credentials and paths, making it suitable for various deployments. It includes a basic query to retrieve the Firebird engine version to confirm connectivity. The example defaults to `firebird-driver` (via `firebird+firebird://`) but notes the `fdb` alternative.

import os
from sqlalchemy import create_engine, text

# Configure Firebird connection details via environment variables
FB_USER = os.environ.get('FIREBIRD_USER', 'sysdba')
FB_PASSWORD = os.environ.get('FIREBIRD_PASSWORD', 'masterkey')
FB_HOST = os.environ.get('FIREBIRD_HOST', 'localhost')
FB_PORT = os.environ.get('FIREBIRD_PORT', '3050')
FB_DB_PATH = os.environ.get('FIREBIRD_DB_PATH', '/opt/firebird/data/employee.fdb') # Example for Linux
# For Windows, path might be 'C:/path/to/my_project.fdb'
# Optional: Specify client library path if needed, e.g., 'C:/Firebird/Firebird_4_0/bin/fbclient.dll'
FB_CLIENT_LIB = os.environ.get('FIREBIRD_CLIENT_LIBRARY', '')

# Construct the connection URI. Use 'firebird+firebird' for firebird-driver (Python 3.8+)
# or 'firebird+fdb' for fdb driver (older Python/Firebird 2.5).
# The 'firebird' driver is assumed to be firebird-driver for Python 3.8+
db_uri_parts = [
    f"firebird+firebird://{FB_USER}:{FB_PASSWORD}@{FB_HOST}:{FB_PORT}{FB_DB_PATH}"
]
if FB_CLIENT_LIB:
    db_uri_parts.append(f"?fb_client_library={FB_CLIENT_LIB}")

db_uri = "".join(db_uri_parts)

print(f"Attempting to connect to: {db_uri.split(':', 2)[0]}://{FB_USER}:****@{FB_HOST}:{FB_PORT}{FB_DB_PATH}")

try:
    engine = create_engine(db_uri, echo=True)

    with engine.connect() as connection:
        # Example: Fetch Firebird engine version
        result = connection.execute(text("SELECT RDB$GET_CONTEXT('SYSTEM', 'ENGINE_VERSION') FROM RDB$DATABASE"))
        version = result.scalar()
        print(f"Successfully connected to Firebird. Engine Version: {version}")
        connection.commit()

except Exception as e:
    print(f"Connection failed: {e}")

view raw JSON →