Executing “SELECT … WHERE … IN …” using MySQLdb

后端 未结 10 2018
耶瑟儿~
耶瑟儿~ 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 22:04

    If you have other parameters in the query, beyond the IN list, then the following extension to JG's answer may be useful.

    ids = [1, 5, 7, 213]
    sql = "select * from person where type=%s and id in (%s)"
    in_ids = ', '.join(map(lambda x: '%s', ids))
    sql = sql % ('%s', in_ids)
    params = []
    params.append(type)
    params.extend(ids)
    cursor.execute(sql, tuple(params))
    

    That is, join all the params in a linear array, then pass it as a tuple to the execute method.

提交回复
热议问题