Niranj Rajasekaran
Niranj Rajasekaran

Reputation: 778

How can I bind a Python list as a parameter in a custom query in SQLAlchemy and Firebird?

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.

Upvotes: 7

Views: 8161

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 53017

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.

Upvotes: 10

Related Questions