MySQLDB - generating "...not in (1,2,3)" from Python list ?

Marc Boeren M.Boeren at guidance.nl
Mon Feb 23 11:26:23 CET 2004


> select * from T where C1 not in (1,2,3)

> cursor.execute("select * from T where C1 not in (%s)",params).

Try this (just some snippets to get you going)

# this is used to translate lists/tuples to (1,2,3) format
# doesn't check to see if contents are actually numeric...
def _converter_set_ids(x, d):
    if not len(x): return "(NULL)"
    return "(%s)" % ", ".join([str(xx) for xx in x])

connection = db.connect(**connectparams)
# map tuples/lists to my own conversion function
connection.converter[types.TupleType] = _converter_set_ids
connection.converter[types.ListType] = _converter_set_ids
cursor = connection.cursor()
cursor.execute("select * from T where C1 not in (%s)", params)


Cheerio, Marc.




More information about the Python-list mailing list