如何在 python psycopg2 raw sql 执行中将 asc desc 作为参数传递?

how to pass asc desc as params in python psycopg2 raw sql execution?

我有一个示例查询模板来接受要执行的动态参数:

ps_conn = psycopg2.connect(...)
ps_cursor = ps_conn.cursor()
ps_cursor.execute('''
    SELECT *
    FROM "posts"
    ) ORDER BY "posts"."rate" %s, "posts"."date_created" ASC LIMIT 1
    ''', ["DESC"])

如您所见,我想将 DESC 动态传递给 orderby 结果,但上面的代码不断抛出错误 InvalidSchemaName

schema "posts" does not exist LINE 11:) ORDER BY "posts"."rate" 'DESC',

它将 DESC 作为 'DESC' 传递给 sql 。

对如何执行此功能以便我可以动态传递订购类型有何看法?

像这样更新您的查询并尝试:

ps_cursor.execute('''
SELECT *
FROM "posts"
) ORDER BY "posts"."rate" {0}, "posts"."date_created" ASC LIMIT 1
'''.format("DESC"))

我会创建一个单独的变量和代码如下:

ps_conn = psycopg2.connect(...)
ps_cursor = ps_conn.cursor()

# you may add a condition to use DESC or not
dynamic_sort = 'DESC'
ps_cursor.execute('''SELECT *
                     FROM posts
                     ORDER BY rate %s, date_created ASC 
                     LIMIT 1''',
                  (dynamic_sort))
ps_conn = psycopg2.connect(...)
ps_cursor = ps_conn.cursor()
ps_cursor.execute('''
    SELECT *
    FROM "posts"
    ORDER BY "posts"."rate" {order}, "posts"."date_created" ASC LIMIT %s
    '''.format(order='desc'),(1,))