The following solution uses the SQLAlchemy expression language and works with SQLAlchemy 1.1. This solution does not mix parameters with the query (as requested by the original author), but provides a way to use SQLAlchemy models to generate SQL query strings and parameter dictionaries for different SQL dialects. The example is based on the tutorial http://docs.sqlalchemy.org/en/rel_1_0/core/tutorial.html
Given the class,
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class foo(Base): __tablename__ = 'foo' id = Column(Integer(), primary_key=True) name = Column(String(80), unique=True) value = Column(Integer())
we can create a query using the select function.
from sqlalchemy.sql import select statement = select([foo.name, foo.value]).where(foo.value > 0)
Next, we can compile the statement into a request object.
query = statement.compile()
By default, the statement is compiled using the base implementation of named, which is compatible with SQL databases such as SQLite and Oracle. If you need to specify a dialect such as PostgreSQL, you can do
from sqlalchemy.dialects import postgresql query = statement.compile(dialect=postgresql.dialect())
Or, if you want to explicitly specify the dialect as SQLite, you can change paramstyle from "qmark" to "named".
from sqlalchemy.dialects import sqlite query = statement.compile(dialect=sqlite.dialect(paramstyle="named"))
From the query object we can extract the query string and query parameters
query_str = str(query) query_params = query.params
and finally complete the request.
conn.execute( query_str, query_params )