我有一个如下所示的 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 + '%']
关于python - psycopg2 转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967669/