57

I have this code:

#! /usr/bin/env python
import MySQLdb as mdb
import sys    

class Test:
    def check(self, search):
        try:
            con = mdb.connect('localhost', 'root', 'password', 'recordsdb');
            cur = con.cursor()
            cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
            ver = cur.fetchone()            
            print "Output : %s " % ver            
        except mdb.Error, e:          
            print "Error %d: %s" % (e.args[0],e.args[1])
            sys.exit(1)            
        finally:    
            if con:    
                con.close()

test = Test()
test.check("test")

But I get an error like:

Traceback (most recent call last):
  File "./lookup", line 27, in <module>
    test.check("test")
  File "./lookup", line 11, in creep
    cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
    query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

What is wrong, and how do I fix it?


The same problem occurs in sqlitem, reported differently; see sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied for details.

4
  • 2
    No need/desire to quote your query parameters. Feb 12, 2014 at 21:51
  • 2
    i.e., cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search]) Feb 12, 2014 at 21:51
  • 2
    I meet this problem while using python2.7, but it's right while using python2.6. Do you know the reason?
    – Matt
    Oct 18, 2017 at 8:48
  • I too faced this issue after upgrading the Ubuntu on our servers from 14.x to 16.x. Would someone be able to explain the version dependencies here? That would be really helpful. Mar 29, 2019 at 12:54

8 Answers 8

117

Instead of this:

cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )

Try this:

cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )

See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).

6
  • I see, so a list must be passed in order for it to work? Feb 12, 2014 at 21:54
  • Also interestingly I can still pass % in input and it will not escape it but rather will use it just like a wildcard Feb 12, 2014 at 21:56
  • @MandatoryProgrammer don't format the query string using %. Use the above method. and from the documentation the DB API requires you to pass in any parameters as a sequence. Feb 12, 2014 at 21:57
  • I'm not, I'm referencing to passing search = "%test%" which works (so users could potentially enumerate my database by injecting percent symbols as input. Feb 12, 2014 at 21:59
  • You should convert your query to text before executing. I've solved my problem using the same. \n >>> from sqlalchemy.sql import text >>> s = text( ... "SELECT users.fullname || ', ' || addresses.email_address AS title " ... "FROM users, addresses " ... "WHERE users.id = addresses.user_id " ... "AND users.name BETWEEN :x AND :y " ... "AND (addresses.email_address LIKE :e1 " ... "OR addresses.email_address LIKE :e2)") SQL>>> conn.execute(s, x='m', y='z', e1='%@aol.com', e2='%@msn.com').fetchall() Jan 27, 2018 at 4:27
29

You can try this code:

cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )

You can see the documentation

4
  • 5
    Adding the comma at the end of the tuple is exactly what I needed.
    – User
    May 10, 2016 at 13:34
  • @User thanks for pointing that out, really helped! In case others want to know; it is because simply adding () around the variable name does not make it a tuple. Adding the comma does
    – Daksh Shah
    Apr 28, 2021 at 16:16
  • I had to add the brackets and the comma to make it work. Mar 24, 2022 at 8:12
7

'%' keyword is so dangerous because it major cause of 'SQL INJECTION ATTACK'.
So you just using this code.

cursor.execute("select * from table where example=%s", (example,))

or

t = (example,)
cursor.execute("select * from table where example=%s", t)

if you want to try insert into table, try this.

name = 'ksg'
age = 19
sex = 'male'
t  = (name, age, sex)
cursor.execute("insert into table values(%s,%d,%s)", t)
1
  • 1
    While true, the opening comment does not explain the issue at hand. OP was already correctly attempting to let the library do the query; the problem was simply that the input wasn't properly wrapped in a singleton tuple. This answer does not cover anything that wasn't already in the answers offered immediately in 2014, and does not explain clearly. Apr 4 at 1:56
3
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )

I do not why, but this works for me . rather than use '%s'.

1
  • This was already explained thoroughly by previous answers. There is no useful explanation here, and also the code does still use %s. Apr 4 at 1:57
2

The accepted answer by @kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.

There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported

cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')

but the 1.2.5 versions require

cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])

as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.

The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.

If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:

$ pip install MySQL-python==1.2.3
1

I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:

mysql> select * from methods limit 1;
+----------+--------------------+------------+
| MethodID | MethodDescription  | MethodLink |
+----------+--------------------+------------+
|       32 | Autonomous Sensing | NULL       |
+----------+--------------------+------------+
1 row in set (0.01 sec)

mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9999'' ' at line 1

Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py where I opened "con" as a connection to my database.

>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"
>>> 

Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:

>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"
>>> 

Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,) or a list [search]. You can try them, but you'll find no difference from the output above.

The best answer is ksg97031's.

1
  • 1
    ksg97031 uses a tuple, too. It's something related to MySQLdb library not the MySQL itself.
    – adonese
    May 18, 2017 at 11:51
1

According PEP8,I prefer to execute SQL in this way:

cur = con.cursor()
# There is no need to add single-quota to the surrounding of `%s`,
# because the MySQLdb precompile the sql according to the scheme type
# of each argument in the arguments list.
sql = "SELECT * FROM records WHERE email LIKE %s;"
args = [search, ]
cur.execute(sql, args)

In this way, you will recognize that the second argument args of execute method must be a list of arguments.

May this helps you.

1

I encountered this error while executing SELECT * FROM table; I traced the error to cursor.py line 195.

if args is not None:
        if isinstance(args, dict):
            nargs = {}
            for key, item in args.items():
                if isinstance(key, unicode):
                    key = key.encode(db.encoding)
                nargs[key] = db.literal(item)
            args = nargs
        else:
            args = tuple(map(db.literal, args))
        try:
            query = query % args
        except TypeError as m:
            raise ProgrammingError(str(m))

Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.