MySqlDb is an excellent Python module -- only one part can be quite annoying. Query parameters seem like this

cursor.execute("select * from Books where isbn=%s", (isbn,))

whereas otherwise within the known world (oracle, sqlserver, access, sybase...) they appear such as this

cursor.execute("select * from Books where isbn=?", (isbn,))

Which means that if you wish to be portable you need to in some way switch between your two notations ? and %s, that is really annoying. (Do not let me know to make use of an ORM layer -- I'll strangle you).

Allegedly you are able to convince mysqldb to make use of the conventional syntax, however i have not yet managed to get work. Any suggestions?

I discovered enough detailed information online available about paramstyle that appeared to imply it may be that which you wanted, but according to this wiki make use of the paramstyle your library uses, and many of them do not let you to definitely change it out:

paramstyle is specific towards the library you utilize, and educational - make use of the main one it uses. This really is most likely probably the most annoying thing about this standard. (a couple of permit you to set different paramstyles, but this is not standard behavior)

I discovered some posts that spoken about MySQLdb permitting this, but apparently it does not as someone indicated it did not work with them.

I do not recommend carrying this out, however the easiest option would be to monkeypatch the Cursor class:

from MySQLdb.cursors import Cursor
old_execute = Cursor.execute
def new_execute(self, query, args):
   return old_execute(self, query.replace("?", "%s"), args) 
Cursor.execute = new_execute

From things i can help you cannot use '?' for any parameter marker with MySQLdb (from box)

you can however use named parameters


cursor.execute("%(param1)s = %(param1)s", {'param1':1})

would effectively execute 1=1

in mysql

but kind of like Eli clarified (although not hackish)

you can rather do:

import MySQLdb.cursors import Cursor

class MyNewCursor(Cursor):
  def execute(self, query, args=None):
     """This cursor is able to use '?' as a parameter marker"""
     return Cursor.execute(self, query.replace('?', '%s'), args)

  def executemany(self, query, args):

within this situation you'd possess a custom cursor which may do what you would like it to complete and it isn't a hack. It is simply a subclass )

and employ it with:

from MyNewCursorModule import MyNewCursor

conn = MySQLdb.connect(...connection information...

(you may also provide the class towards the connection.cursor function to produce it there if you wish to make use of the normal execute more often than not (a temp override)) may also alter the simple alternative to something a bit more correct (presuming there's a method to escape the question mark), but that's something I'll leave your decision :)