views:

204

answers:

5
A: 

You could substitute your variables before passing the query string to execute():

query = """SELECT * FROM sometable 
                    order by %s %s 
                    limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
# This will pass a copy of query with all %s's substituted
cur.execute(query % (sortname, sortorder, limit1, limit2) )
results = cur.fetchall()
Shirkrin
What about SQL-injection?
Yaroslav
In case you can't trust or validate you substitutions you should'nt use this ;)
Shirkrin
The problem here that trusted and untrusted input is mixed inside one statement.
Yaroslav
A: 

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) ) 
unutbu
A: 

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))
naivnomore
You should note that this will only work in >= python 2.6 -- which not everyone is using by now.
Shirkrin
+1  A: 

%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

Yaroslav