SilentGhost
2010-03-29 13:55:11
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
2010-03-29 13:55:21
What about SQL-injection?
Yaroslav
2010-03-29 13:56:38
In case you can't trust or validate you substitutions you should'nt use this ;)
Shirkrin
2010-03-29 14:00:53
The problem here that trusted and untrusted input is mixed inside one statement.
Yaroslav
2010-03-29 14:02:16
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
2010-03-29 13:57:20
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
2010-03-29 13:57:28
You should note that this will only work in >= python 2.6 -- which not everyone is using by now.
Shirkrin
2010-03-29 13:59:39
+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
2010-03-29 14:00:59