python - psycopg2 转义字符

标签 python postgresql psycopg2

我有一个如下所示的 postgres 查询,并在 psql 上运行查找:

select 
    gcaseid,
    count (*)                          as N,
    array_agg(distinct nvchquestion)   as questions,
    array_agg(nvchanswer)              as answers
from
    case_script,
    case_script_answer
where
    case_script.gscriptid = case_script_answer.gscriptid and
    nvchquestion ilike '%blood pressure%'
group by
    gcaseid
order by
    N desc
;

现在,我想在 Python 中进行类似的查询,这就是我想出的:

import psycopg2

def getAnswers(question):

    query = '''
            select 
                gcaseid,
                count (*)                          as N,
                array_agg(distinct nvchquestion)   as questions,
                array_agg(nvchanswer)              as answers
            from
                case_script,
                case_script_answer
            where
                case_script.gscriptid = case_script_answer.gscriptid and
                nvchquestion ilike %s
            group by
                gcaseid
            order by
                N desc
            ;
    '''%(r"'%%s%'")

    conn = psycopg2.connect("dbname='sos' user='postgres' host='localhost'")
    cur  = conn.cursor()

    cur.mogrify(query, (question,))
    # cur.execute(query, (question,))

    # result = cur.fetchall()

    cur.close()
    conn.close()

    return result

if __name__ == '__main__':

    print getAnswers('blood pressure')
    print 'done'

现在,当我运行这个查询时,我得到了错误:

$ python updateTable.py
Traceback (most recent call last):
  File "updateTable.py", line 39, in <module>
    print getAnswers('blood pressure')
  File "updateTable.py", line 27, in getAnswers
    cur.mogrify(query, (question,))
ValueError: unsupported format character ''' (0x27) at index 442

不确定发生了什么。有谁可以澄清一下吗?

最佳答案

在查询中使用 %% 来表示 LIKE 通配符:

execute(" ... ilike %%%s%%", [question])

或者用 % 包围您的值:

execute(" ... ilike %s", ['%' + question + '%']

参见 docs about parameters .

关于python - psycopg2 转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967669/

相关文章:

python - Python/psycopg2 中的优雅主键错误处理

python-2.7 - 编程错误: close cannot be used while an asynchronous query is underway

python - 尝试解决将字符串转换为列表中的整数时遇到不同的错误

Postgresql:按 CompanyID 和 CustomerID 删除重复记录

sql - 需要将单词转换为字符串以在 ruby​​ 中通过 sql 进行搜索

java - 使用 JOOQ 在 "not in"子句中指定多个列进行删除

sql - 使用 Psycopg2 和 Greenplum 数据库获取最后插入的行 ID

python - 多尺度 CNN - Keras 实现

python - python-pillow 中内核大小大于 5x5 的卷积

python - 如何用逗号交换名字和姓氏并添加新列?