-1

When I was trying to use the following SQL to fetch some result from MySQL database,

entries = db.query("SELECT * FROM users ORDER BY created_at DESC LIMIT %s", count)

I got this error:

File "/Library/Python/2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue ProgrammingError: (1064, "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 ''20'' at line 1")

I really don't know what's wrong with my SQL script. Actually, it worked pretty well in my previous PHP version of the server. Why it doesn't work in my Python version? Has it anything specific related to the Tornado database wrapper?

I tried to search the whole Internet, no luck. :(

3
  • count = 20 in this context. the error message actually got its value as 20.
    – horacex
    Aug 23, 2012 at 16:11
  • This works for me (Python 2.7, Tornado 2.3, MySQLdb 1.2.3) Aug 24, 2012 at 4:14
  • python 2.7.3, Tornado 2.3, MySQLdb 1.2.3
    – horacex
    Aug 25, 2012 at 11:11

1 Answer 1

2

You're using '%s' placeholder, so count value (which is obviously 20) gets quoted (which makes your query end with LIMIT '20'). Try using '%d' instead.

Well, as Cole Maclean said, you can't use non-'%s' placeholders here; that makes my solution a bit wrong, to say the least.

Yet the reason is still the same: LIMIT parameter should be a number, not 'numeric string'. But the quotation marks somehow reach the final query: MySQL error message is clearly about LIMIT '20' line.

That, in turn, may be caused by either a bug in MySQLdb library, or - perhaps - wrong value given to count variable: string '20' (with quotation marks as part of it) instead of number 20. I admit, both cases seem unlikely to me.

Can you test this query with hard-coded literal in place of count? Like...

db.query("SELECT * FROM users ORDER BY created_at DESC LIMIT %s", 20)
5
  • While %d would be logical, MySQLdb only works with %s placeholders. Aug 24, 2012 at 4:12
  • @ColeMaclean Updated the answer. I'm a bit confused about it, as the error message points to LIMIT problem here.
    – raina77ow
    Aug 24, 2012 at 6:09
  • Yeah, maybe you're right about count actually being "'20'". Aug 24, 2012 at 6:28
  • thanks a lot for the help! I modified my method to remove "count" argument. just put 20 there in the method body query. it went through without any error. This is really strange. I checked many other places it says only %s is allowed for db query, %d is not used in such context.
    – horacex
    Aug 25, 2012 at 11:07
  • Check where you are setting count. Make you have it as count = 20 or something like that. Not count = '20' That is likely the issue
    – Drahkar
    Aug 26, 2012 at 12:18

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