6

How do I do this correctly:

I want to do a query like this:

query = """SELECT * FROM sometable 
                    order by %s %s 
                    limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (sortname, sortorder, limit1, limit2) ) 
results = cur.fetchall()

All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them.

So it ends up like:

ORDER BY 'somecol' 'DESC'

Which is wrong should be:

ORDER BY somecol DESC

Any help greatly appreciated!

0

4 Answers 4

9

paramstyle
Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.

Sign up to request clarification or add additional context in comments.

Comments

6

%s placeholders inside query string are reserved for parameters. %s in 'order by %s %s' are not parameters. You should make query string in 2 steps:

query = """SELECT * FROM sometable order by %s %s limit %%s, %%s;"""
query = query % ('somecol', 'DESC')
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (limit1, limit2) ) 
results = cur.fetchall()

DO NOT FORGET to filter first substitution to prevent SQL-injection possibilities

Comments

0

Not all parts of an SQL query can be parametrized. The DESC keyword for example is not a parameter. Try

query = """SELECT * FROM sometable 
                    order by %s """ + sortorder + """
                    limit %s, %s"""

cur.execute(query, (sortname, limit1, limit2) ) 

Comments

-1

You could try this alternatively...

query = """SELECT * FROM sometable 
                    order by {0} {1} 
                    limit {2}, {3};"""

sortname = 'somecol'
sortorder = 'DESC'
limit1 = 'limit1'
limit2 = 'limit2'

print(query.format(sortname, sortorder, limit1, limit2))

2 Comments

You should note that this will only work in >= python 2.6 -- which not everyone is using by now.
Also note that this is an incorrect solution for when the values are not controlled, due to the possibility of SQL injection attacks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.