EscapingMySQLdbQueries

From XPUB & Lens-Based wiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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.