MySQLdb, escaping values
John Hunter
jdhunter at ace.bsd.uchicago.edu
Wed May 7 08:06:23 EDT 2003
>>>>> "Skip" == Skip Montanaro <skip at pobox.com> writes:
Skip> db = MySQLdb.Connection(...) n = raw_input("Enter a
Skip> name: ").strip() curs = db.cursor() print
Skip> curs.execute("select * from people where name = %s", (n,))
Skip> Note that the second arg must be a tuple, even if you are
Skip> only passing a single parameter.
I have noticed a bug before where integers were not properly escaped in
my version of mysqldb (or else I'm missing something obvious). For
example, both
c.execute('select * from image where pid=%d', (1234,))
c.execute('select * from image where pid=%d', 1234)
generate the exception
Traceback (most recent call last):
File "mysql_demo.py", line 10, in ?
c.execute('select * from image where pid=%d', (1234,))
File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in execute
return self._execute(query, args)
File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 110, in _execute
self.errorhandler(self, TypeError, m)
File "/usr/lib/python2.2/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler
raise errorclass, errorvalue
TypeError: an integer is required
but this call works as expected:
c.execute('select * from image where pid=%d' % 1234)
So I often use a hybrid of python and mysql string format capabilities
as a workaround.
JDH
More information about the Python-list
mailing list