Menu

#331 SELECT IN a list with only one element

MySQLdb-1.2
open
nobody
None
1
2017-03-29
2013-04-23
T.L.
No

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!

Discussion

  • Robert Penz

    Robert Penz - 2017-03-29

    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

     
  • Robert Penz

    Robert Penz - 2017-03-29

    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

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.