MySQLdb, escaping values

Gilles Lenfant glenfant at NOSPAM.bigfoot.com
Wed May 7 09:02:15 EDT 2003


"Dave Harrison" <dave at nullcube.com> a écrit dans le message de news:
mailman.1052306713.13950.python-list at python.org...
> hey,
>
> Ive written a web/db app, but I want to make sure that I am appropriately
escaping the strings that I am writing to the database fields.
>
> I can't seem to find a method to escape strings for MySQL in the MySQLdb
library though.
>
> Suggestions ?
>
> Cheers
> Dave
>

Don't care about escaping usual types. MySQLdo connection objects do this
for you in a transparent way.
You need mx.DateTime to have python/MySQL datetime automatic/transparent
conversions.

You can even add your own (un)escapers converters for your app objects.

Example in one of my apps to convert from unicode for varchar fields

from MySQLdb import converters
import types
...
def isoEncode(val, dummyDict):
    '''Recode en iso-8859 tout objet en unicode
    '''
    try:
        return converters.Thing2Literal(val.encode('iso-8859-1'), dummyDict)
    except UnicodeError:
        for c in val:
            print c,
        exit(0)
...
myConverter = {types.UnicodeType: isoEncode}
myConverter.update(converters.conversions)
...
Cnx = MySQLdb.Connect(host='localhost', db='mybase', user='xxx',
passwd='...', conv=myConverter)

HTH

--Gilles





More information about the Python-list mailing list