Avec le support de Firebird :
pip install sqlalchemy fdb sqlalchemy-firebird
Tester la version :
import sqlalchemy
sqlalchemy.__version__
from sqlalchemy import create_engine import sys # Paramètres de connexion user_name = "sysdba" password = "masterkey" server = "localhost" dbpath = "c:/path/to/database.fdb" # sous Linux : "/path/to/database.fdb" # Chemin vers la librairie cliente fb_library_name = sys.path[0] + '\\fbclient.dll' engine = create_engine("firebird+fdb://%s:%s@%s/%s?fb_library_name=%s" % ( user_name, password, server, dbpath, fb_library_name ))
Requête Select :
from sqlalchemy import text with engine.connect() as conn: result = conn.execute(text("select id, nom from clients order by nom")) # Afficher tous les résultats dans une liste de tuples : print(result.all()) # Parcourir le résultat et afficher les lignes individuellement : for row in result: print(f"{row.id} : {row.nom.strip()}")
Requêtes transactionnelles avec un commit() à la fin :
from sqlalchemy import text with engine.connect() as conn: conn.execute(text("CREATE TABLE some_table (x int, y int)")) conn.execute( text("INSERT INTO some_table (x, y) VALUES (:x, :y)"), [{"x": 1, "y": 1}, {"x": 2, "y": 4}], ) conn.commit()
Requêtes transactionnelles dans un bloc begin() (le commit se fait implicitement) :
from sqlalchemy import text with engine.begin() as conn: conn.execute( text("INSERT INTO some_table (x, y) VALUES (:x, :y)"), [{"x": 1, "y": 1}, {"x": 2, "y": 4}], )
from sqlalchemy import Column, Integer, String from sqlalchemy.orm import declarative_base Base = declarative_base() class User(Base): __tablename__ = "mytable" id = Column(Integer, primary_key=True) name = Column(String(100)) def __repr__(self): return u"<User (%d)%s>" % (self.id, self.name.strip())
from sqlalchemy import select stmt = select(User).where(User.id < 20) users = session.scalars(stmt).all() for user in users: print(user)