SELECT IN a list with only one element
MySQL database connector for Python programming
Brought to you by:
adustman
Hi,
I found a bug when running this bit of code in a Python console (Python 2.7.3). The point here is that I want to be able to select "in" a list, even when said list has only one element.
import MySQLdb db = MySQLdb.connect({user: %%%, passwd: %%%; db: %%%, host: %%%, port: %%%}) cursor = db.cursor() query = """SELECT 1 in %s""" list_one = [1] list_two = [1, 2] try: cursor.execute(query, (list_one,)) print "Query ok with %s." % list_one except Exception as e: print "Query not ok with %s with exception %s." % (list_one, str(e)) try: cursor.execute(query, (list_two,)) print "Query ok with %s." % list_two except Exception as e: print "Query not ok with %s with exception %s." % (list_two, str(e))
A fix for this would be in cursor.py (line 159)
current:
query = query % db.literal(args)
fix:
if isinstance(args, dict): query = query % {key: db.literal(item) for key, item in args.iteritems()} else: query = query % tuple([db.literal(item) for item in args])
Or am I missing a possible alternative syntax ?
Thanks a lot for your time!
This patch breaks stuff that worked with the previous version of mysql-python
eg.
cursor.execute("SELECT %s ...), (aString))
TypeError: not all arguments converted during string formatting
or
cursor.execute("SELECT %s ...), aString)
TypeError: not all arguments converted during string formatting
A correct solution would be
if isinstance(args, dict):
query = query % {key: db.literal(item) for key, item in args.iteritems()}
elif isinstance(args, tuple):
query = query % tuple([db.literal(item) for item in args])
else:
query = query % db.literal(args)
Last edit: Robert Penz 2017-03-29