如何将ASC DESC作为Python Psycopg2 Raw SQL执行中的参数传递?

发布于 2025-01-26 11:07:03 字数 433 浏览 4 评论 0原文

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

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"])

正如您所看到的,我想动态地传递到结果,但是上面的代码继续抛出错误

架构“帖子”不存在 第11行:)按“帖子”订单。“速率”'desc',

它以'desc'的方式将desc传递给SQL。

有任何意见如何执行此功能,以便我可以动态地传递订购类型?

i have a sample query template to accept dynamic parameters to execute:

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"])

as you can see i wanna pass DESC dynamically to orderby the results , but the above code keep throwing the error InvalidSchemaName

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

it passes the DESC as 'DESC' to the sql .

any opinion how to perform this functionality so i can pass ordering type dynamically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十六岁半 2025-02-02 11:07:03

这样更新您的查询,然后尝试:

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

Update your query like this and try:

ps_cursor.execute('''
SELECT *
FROM "posts"
) ORDER BY "posts"."rate" {0}, "posts"."date_created" ASC LIMIT 1
'''.format("DESC"))
染墨丶若流云 2025-02-02 11:07:03

相反,我将创建一个单独的变量和代码如下:

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))

I would instead create a separate variable and code as follows:

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))
情魔剑神 2025-02-02 11:07:03
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,))
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,))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文