mongotop mongotop - 1 year ago 56
Python Question

How to pass IN or NOT IN clause as variable to postgresql query using python

How to pass

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

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,))

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download