Search code examples
pythonmysqlpymysql

Python and MySQL: passing a list / tuple


I am building a query in Python to pass to a pymysql query.

condition=['m']
query = "select * from table where condition in {}'.format(tuple(condition))

The part I am stuck on is that I want to set up the script to work both for situation where condition can be a single item, or have multiple items.

Seemed to me that getting a list converted into a tuple would work, but it does not, because: tuple(condition) returns: ('m',) , which fails to work on my mysql server.

What is the easiest way to set this up that I can sent either a single value, or multiple values to the where clause on my query build in python?


Solution

  • So I went with a different route, since these suggestions were either too cumbersome, or did not work.

    The solution that worked for me is this: cond = ', '.join('"{0}"'.format(w) for w in condition)

    and then the query is: select * from table where condition in ({}).format(cond)`

    This generates a string of comma separated values, each value surrounded by quotation marks. Example:

    condition = ['baseline', 'error']
    cond = ', '.join('"{0}"'.format(w) for w in condition)   
    #"baseline","error"  
    query = select * from table where condition in ({})`.format(cond)   
    # select * from table where condition in ("baseline","error")