2017-03-23 1 views
0

나는 다음과 같은 포스트 그레스 쿼리를 가지고 있고, 실행은 psql의에 발견 :psycopg2 탈출 문자

$ 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 

하지 무슨 일이 일어나고 있는지 확인 :이 쿼리를 실행할 때

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' 

지금, 나는 오류가 발생했습니다. 누구든지 명확하게 설명 할 수 있습니까?

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

을 아니면 값 %의하여 값을 둘러싸고 : 귀하의 요청에

답변

2

사용 %%LIKE wildchars를 대표하는

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

docs about parameters를 참조하십시오.

+0

감사! 이것은 내가 결국 사용하는 것입니다! – ssm

1

간단한 그것을 전달하는 매개 변수에 연결된 %@piro에 의해 제안 :

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

출력 :

select 'x' ilike '%x%' 
True 

하지만 당신은 매개 변수를 깨끗하게 사용 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