8

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?

1

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You should try this method:

args = [1, 2, 3]
raw_sql = "SELECT * FROM table WHERE data IN %s" 
params = [(args,)] # the comma allows to convert the list into a tuple
conn.engine.execute(raw_sql, params)

5 Comments

Hello @Jivan, thanks for the answer, but I am afraid that converting it to a string won't work. I am getting the MySQL error code: 1064. Even if I try the SQL syntax in MySQL Workbench. I am getting the same error. It's not allowing me to write IN "(1, 2, 3)" or IN '(1, 2, 3)' and if I remove the str method I am still getting the same error! it i also underlined in MySQL Workbench that the "" is an SQL syntax error
@Sigils ok I found another method. Just edited my answer to reflect that.
I am sorry but that did neither work. I am really glad that you are taking your time and trying to help me. But the error I am getting now is AttributeError: 'list' object has no attribute 'keys'. I am using python 3.4 if that matters? And yes I did write exactly how you did! Perhaps I should write it with ORM instead of RAW SQL?
@Sigils at which line exactly are you getting your AttributeError?
I am using WSGI application to show the errors. Not getting any line errors. But the last traceback error was keys = distilled_params[0].keys() builtin code for SQLAlchemy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.