问题
Environment
I am using Firebird database with SQLAlchemy as ORM wrapper.
Backgound
I know that by using in_ it is possible to pass the sales_id list in IN clause and get the result.
I have a use case where I must use textual sql.
Question
Here is my snippet,
conn.execute('select * from sellers where salesid in (:sales_id)', sales_id=[1, 2, 3] ).fetchall()
This always throws token unknown error
All I need is to pass the list of sales_id ([1, 2, 3]) to bind parameter (:sales_id) and get the result set.
回答1:
If using a DB-API driver that does not provide special handling of tuples and lists for producing expressions for row constructors and IN predicates, you can use the somewhat new feature "expanding" provided by bindparam:
stmt = text('select * from sellers where salesid in :sales_id')
stmt = stmt.bindparams(bindparam('sales_id', expanding=True))
conn.execute(stmt, sales_id=[1, 2, 3]).fetchall()
This will replace the placeholder sales_id on a per query basis by required placeholders to accommodate the sequence used as the parameter.
来源:https://stackoverflow.com/questions/55811285/how-can-i-bind-a-python-list-as-a-parameter-in-a-custom-query-in-sqlalchemy-and