Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy and RAW SQL: List as an input

I am using Flask-SQLAlchemy, and I am having some trouble with the IN clause in the SQL syntax. The data I want my IN clause to "read" is a list with some data, for example

args = [1, 2, 3]

here is how my code looks like.

connection = db.session.connection()
raw_sql = text("""
        SELECT
          *
        FROM 
         table
        WHERE data IN :list
        """)
query = connection.engine.execute(raw_sql, {'list' : args})

I have tried giving inserting tuples and list to the args parameter, but nothing have worked. I am either getting:

  • Python 'tuple' cannot be converted to a MySQL type with args = tuple([1, 2, 3])
  • Python 'list' cannot be converted to a MySQL type, when using args = [1, 2, 3]


how do you read from a list with SQLAlchemy and using RAW SQL and parameters as an input?

like image 693
Sigils Avatar asked Jun 24 '26 06:06

Sigils


1 Answers

On python 3.7:

import sqlalchemy

args = [1, 2, 3]
raw_sql = "SELECT * FROM table WHERE data IN :values" 
query = sqlalchemy.text(raw_sql).bindparams(values=tuple(args))
conn.engine.execute(query)
like image 142
mateus_pd Avatar answered Jun 25 '26 19:06

mateus_pd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!