﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
20115	Error with MySQL database using % in direct SQL	Evgeniy Makhmudov	nobody	"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)
{{{
#!python
from django.db import connection
...
cursor=connection.cursor()
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:
{{{
django/db/backends/util.py:36

def execute(self, sql, params=()):
}}}
and some levels bottom it invoke this:
{{{
MySQLdb/cursors.py:139

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:
{{{#!python
'SELECT * from `test`.`test_table` WHERE name LIKE ""Jo%"";'%()
Traceback (most recent call last):
  File ""/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py"", 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 
{{{#!python

from django.db import connection
...
cursor=connection.cursor()
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/util.py:36 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.


"	Bug	closed	Database layer (models, ORM)	1.5	Normal	duplicate	db, error		Unreviewed	1	0	0	0	1	0
