1

How to pass IN OR NOT IN clause as variable to a query?

When I pass the variable in the query bellow I get :

SELECT * FROM table_name WHERE column_name 'IN' ('product', 'category')

which triger an error for the presence of quotes 'IN'

query_clause = 'IN' 
##query_clause could equal 'NOT IN'

cur = my_connection.cursor()
cur.execute("SELECT * FROM table_name WHERE column_name %s ('product', 'category')", (query_clause,))

2 Answers 2

4

Yes, that's expected. Use a boolean parameter instead:

SELECT * FROM table_name
  WHERE (column_name IN ('product', 'category')) = %s

You can then pass true or false into the parameter.

Sign up to request clarification or add additional context in comments.

2 Comments

oh thats a great solution to sanitize user input for this
Thank you Dietrich! That is a VERY cleaver solution and work around!! it did work like charm :)
2

you cant use a sql format string for that ... just a normal format string

cur.execute("SELECT * FROM table_name WHERE column_name %s ('product', 'category')"%(query_clause,))

its worth noting this assumes query_clause is trusted input ... (it will not sanitize against injection if this is not trusted input)

2 Comments

Thank you Joran! you are right, its gonna be open to sql injection if we use %s.
an ORM is usually the real solution ;)

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.