Executing “SELECT … WHERE … IN …” using MySQLdb

后端 未结 10 2012
耶瑟儿~
耶瑟儿~ 2020-11-29 21:23

I\'m having a problem executing some SQL from within Python, despite similar SQL working fine from the mysql command-line.

The table looks like this:

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 21:53

    Unfortunately, you need to manually construct the query parameters, because as far as I know, there is no built-in bind method for binding a list to an IN clause, similar to Hibernate's setParameterList(). However, you can accomplish the same with the following:

    Python 3:

    args=['A', 'C']
    sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
    in_p=', '.join(list(map(lambda x: '%s', args)))
    sql = sql % in_p
    cursor.execute(sql, args)
    

    Python 2:

    args=['A', 'C']
    sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
    in_p=', '.join(map(lambda x: '%s', args))
    sql = sql % in_p
    cursor.execute(sql, args)
    

提交回复
热议问题