Some More MySQL

Kushal Kumaran kushal.kumaran+python at gmail.com
Fri May 28 08:58:29 EDT 2010


On Fri, May 28, 2010 at 5:46 PM, Victor Subervi <victorsubervi at gmail.com> wrote:
> On Fri, May 28, 2010 at 2:17 AM, Dennis Lee Bieber <wlfraed at ix.netcom.com>
> wrote:
>>
>> On Thu, 27 May 2010 23:22:24 +0100, MRAB <python at mrabarnett.plus.com>
>> declaimed the following in gmane.comp.python.general:
>>
>> >
>> > Placeholders which are handled by .execute shouldn't be wrapped in
>> > quotes, even is the value is a string, because .execute will handle that
>> > (and any other details) itself.
>>
>>        Even more internal details -- the MySQLdb placeholder is %s because
>> the adapter, internally, converts ALL parameters to strings, applies
>> escapes to them, and THEN wraps them with quotes before using Python
>> string interpolation to make the query that gets submitted to the
>> server.
>>
>>        This is why you can not use, say %d as a placeholder for a numeric
>> parameter... MySQLdb will convert that numeric to a string, and then
>> Python will choke when it tries to use a %d formatter and is given a
>> string value.
>>
>>
> All of your and MRAB's comments were very helpful. However, I don't see how
> these two problems are addressed:
>
>       sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
> opTable[1:])
> #      cursor.execute(sql, id)
>       cursor.execute('select * from options%s where ID=%s' %
> (opTable[0].upper() + opTable[1:], id))
>

The second argument to cursor.execute needs to be a tuple.  Change the
call to this:

cursor.execute(sql, (id,))

> The last one works, but if I comment it out and uncomment the middle line,
> it doesn't. Same here:
>
>         sql = "update options%s set PriceDiff='%%s' where Field='%%s' and
> ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:])
> #        cursor.execute(sql, (value, opName, id, store))
>         cursor.execute('update options%s set PriceDiff="%s" where Field="%s"
> and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value,
> opName, id, store))
>

Lose the quotes around the %s.  You are replying to a post that
describes why this is important.

-- 
regards,
kushal



More information about the Python-list mailing list