【问题标题】:Why do I get an error when I try to execute a query with parameters in postgreSQL?当我尝试在 postgreSQL 中使用参数执行查询时,为什么会出现错误?
【发布时间】:2010-10-31 21:37:51
【问题描述】:

数据库是 PostgreSQL。当我尝试使用参数执行查询时,例如这个

cursor.execute("""
    SELECT u.username, up.description, 
        ts_rank_cd(to_tsvector(coalesce(username,'')|| coalesce(description,'')) , to_tsquery('%s')) as rank

        FROM auth_user u INNER JOIN pm_core_userprofile up on u.id = up.user_id
        WHERE to_tsvector(coalesce(username,'')|| coalesce(description,'')) @@ to_tsquery('%s')
        ORDER BY rank DESC;
    """, ["hello","hello"])

Django 抱怨 ProgrammingError,在参数处或附近添加语法错误(在本例中为“hello”)。这是错误来自的 Django 生成的 SQL 语句的一部分:

to_tsquery('E'hello'')

即使我将它复制粘贴到 postgreSQL shell,我也会收到语法错误。如果我省略“E”部分,它会起作用。我该怎么做?

【问题讨论】:

    标签: django postgresql django-orm


    【解决方案1】:

    奥兹古尔,

    试试

    to_tsquery(%s)
    

    而不是

    to_tsquery('%s')
    

    【讨论】:

    • 谢谢!这很尴尬,我想我最好尽快休假:)
    • 如果我猜错了会更尴尬...我更习惯 SQL Server 语法。 ;)
    【解决方案2】:

    我相信你在 E 之后缺少一个 '。

    【讨论】:

    • E 的东西是 Django ORM 放在那里的,我只是传递一个字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2017-06-20
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多