Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#20115 closed Bug (duplicate)

Error with MySQL database using % in direct SQL

Reported by: Evgeniy Makhmudov Owned by: nobody
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords: db, error
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no


Hello everybody! Привет всем русскоговорящим в отдельности!

I found problem in Django 1.4.2 and current version in main branch of git repo.

I try to do something like this: (found names that starts with string "Jo", like Joe,John etc)

from django.db import connection
cursor.execute('SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";')

and take exception:
Exception raised: <type 'exceptions.TypeError'> not enough arguments for format string

looks very strange... after time, i found the root of problem.

when execute() method start he invoke this:


def execute(self, sql, params=()):

and some levels bottom it invoke this:


def execute(self, query, args=None):
        if args is not None:
            query = query % db.literal(args)

Look with attention on default values of argument of functions. When i do in my code execute() additional args set by default to turple (), BUT MySQLdb in his execute method waiting None value as default. Next, if my SQL code contain a % symbol (not in placeholder meaning), that MySQLdb execute() method think that i send additional arguments to paste in SQL and do formatting. At this moment raise error because this is wrong Python code:

'SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";'%()
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/IPython/core/", line 2538, in run_code
    exec code_obj in self.user_global_ns, self.user_ns
  File "<ipython-input-1-4ae0cf876369>", line 1, in <module>
    'SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";'%()
TypeError: not enough arguments for format string

In confirmation of the foregoing, if change my code to

from django.db import connection
cursor.execute('SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";', None)

that it will be work properly.

So, as a result, I propose to think about correction file django/db/backends/ to

def execute(self, sql, params=None):

But i don't know about how it will be worked with another DB such Oracle, PostgreSQL. In some reason on SQLite original code don't raise exception.

Change History (2)

comment:1 Changed 4 years ago by Claude Paroz

Resolution: duplicate
Status: newclosed

Duplicate of #9055

comment:2 Changed 4 years ago by Evgeniy Makhmudov

a problem has 5 years old??? oh, sh... Guys, seriously, somebody must solve this not big problem.

Note: See TracTickets for help on using tickets.
Back to Top