safely specifying 'order by' clause from u

2019-07-23 09:15发布

i feel like this is a stupid question but i can't find anything anywhere.

I want to build an SQL query using psycopg2 where the user specifies the sort / order by column.. client-side its a javascript grid of data offering sorting / paging etc.

normal substitution practice doesn't work: (note the E'xx')

cur.mogrify('select * from table offset %s limit %s order by %s', [0,5,'sort_column'])
>>> "select * from table offset 0 limit 5 order by E'sort_column'"

short of cleansing / substituting the order by clause in myself, what is the recommended way to do this ?

am i a duplicate of: psycopg2 E' on table, field and schema ?

cheers

-i

1条回答
家丑人穷心不美
2楼-- · 2019-07-23 09:25

Entity names (tables/columns etc...) in Python's DBAPI shouldn't be run through any place holder processing as variables are supposed to be. You will have to do your own formatting:

'select * from table offset %s limit %s order by %s' % (0,5,'sort_column')

But do use the proper escaping/placeholder functions for WHERE var = %s etc...

查看更多
登录 后发表回答