psycopg2转义字符

2024-09-28 01:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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中有一个类似的查询,这是我想到的:

^{pr2}$

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

$ 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

不知道发生了什么。有人可以澄清一下吗?在


Tags: answerpybyaslinescriptarrayagg
2条回答

按照@piro的建议,传递连接到参数的%最简单的方法是:

query = "select 'x' ilike %s"
print (cursor.mogrify(query, ('%x%',)).decode('utf8'))
cursor.execute(query, ('%x%',))
print (cursor.fetchone()[0])

输出:

^{pr2}$

但是,如果要保持参数的干净,请使用format

query = "select 'x' ilike format('%%%%%%1$s%%%%', %s)"
print (cursor.mogrify(query, ('x',)).decode('utf8'))
cursor.execute(query, ('x',))
print (cursor.fetchone()[0])

输出:

select 'x' ilike format('%%%1$s%%', 'x')
True

在查询中使用%%表示LIKEwildchars:

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

或者在值中用%s将值括起来:

^{pr2}$

参见docs about parameters。在

相关问题 更多 >

    热门问题