Inforian
Inforian

Reputation: 1736

Syntax Error in raw MySQL query in Django

I am using raw mysql queries in django with limit (The limit is dynamic and to be mentioned in Url) such as.

cursor.execute("some select query limit %s " , [limit_value] )

This limit value is comes from the URL www.asd.com/qwe/?limit=5 and I catch this value as limit_value=request.GET.get('limit') and when i print this limit value it will print 5 means I can get the limit value from URL but when I mentioned it in select query as I have shown above. It will throw the error

(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 ''5'' at line 1")

But if I mentioned limit value in file as limit_value=5 and use it in select query as I have shown above it will work.

So it means limit in select query will not work if I mentioned it in URL and catch it into file. WHY? Or there is anything I am missing?

My query:

SELECT DISTINCT 
    A.entity_id AS entity_id, 
    A.email AS email,
    A.catquizid AS style_quiz_score,
    A.catquizquesans AS style_quiz_answer,
    A.created_at AS date_joined,
    A.is_active AS is_active,
    B.attribute_id AS attribute_id,
    B.value AS info
FROM customer_entity AS A
inner join  customer_entity_varchar AS B on A.entity_id=B.entity_id 
WHERE B.attribute_id
limit %s

Upvotes: 0

Views: 951

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121346

Your limit_value is a string, not an integer, and as a SQL parameter it is thus given quotes.

Try this:

cursor.execute("some select query limit %s", (int(limit_value),))

Upvotes: 4

Related Questions