How To/python/

Raw SQL in SQLAlchemy

Poniżej kilka sposobów na używanie czystego sql q SqlAlchemy. Zakładam, ze engine bazy i sesja zostały już stworzone, np:

engine = create_engine('sqlite:///products.db', echo=True)
Session = sessionmaker(bind=engine)

Sposób 1 - wykorzystanie dbapi

conn = engine.connect()
conn.detach()  # detaches the DBAPI connection from the connection pool
cursor = conn.connection.cursor()
cursor.execute('select * from products')
result = cursor.fetchall()
for i in result:
    print i
conn.close()  # connection is closed for real, the pool replaces it with a new connection'''

Sposób 2 - wykorzystanie obiektu sesji Session() i metody connection()

session = Session()
for i in session.connection().execute('SELECT * FROM products where where id > :proid', {'proid':1000}):
    print i