EscapingMySQLdbQueries: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "= Escaping MySQLdb queries = Python's MySQLdb library includes the ability to escape values in queries. You should definitely make use of them as they also protect against inj...")
 
(No difference)

Latest revision as of 21:32, 23 September 2010

Escaping MySQLdb queries

Python's MySQLdb library includes the ability to escape values in queries. You should definitely make use of them as they also protect against injection attacks when producing queries from say form/url supplied data.

a "real world" example:

q = "UPDATE "+MEDIA_TABLE+" SET mediatype='video', filesize=%s, filelastmod=%s, width=%s, height=%s, duration=%s, fps=%s, videoinfo=%s, audioinfo=%s WHERE filename=%s"

cursor.execute(q, (filesize, filelastmod, ffmpeg.get('width'), ffmpeg.get('height'), ffmpeg.get('duration'), ffmpeg.get('fps'), ffmpeg.get('video'), ffmpeg.get('audio'), path))


keep in mind

  • You use %s for all parameters regarless of their type (so also for numbers). The library handles the proper type conversion.
  • You do NOT use actual quotes (' or ") in the query. The library adds these as necessary.