簡體   English   中英

使用cursor.execute()時出現格式錯誤

[英]Formatting Errors when using cursor.execute()

這是一段代碼,給我帶來麻煩

def process_message( msg):
    # deserialize msg
    id_dict = json.loads(msg)
    # extract id

    report_id = id_dict['id']
    print report_id
    sql = """ select  r.id,
            format('DATA "the_geom from (%s) as subquery
            using unique gid using srid=4326"', replace(replace(sql,'<<','%%'),'>>','%%')) as data,
            rcode,
            format('  VALIDATION
            ''userid'' ''^\d+$''
%s
  END',string_agg(format ('    ''%s'' ''%s''', paramname, prompt[1]),'
')) as validation
FROM report.reports r
JOIN report.reportparams rp on r.id = rp.reportid and not rp.del
where r.id = %s
group by r.id, sql, rcode;"""
    args = ('%s','%s','%s','%s','%s')
    cursor.execute(sql, args)
    row = cursor.fetchone()
    (id,data,rcode,validation) = row
    print (id,data,rcode,validation)
    exit

運行代碼時,這是出現的錯誤消息

Traceback (most recent call last):
  File "mapfile_queue_processor.py", line 60, in <module>
    process_message(  content  )
  File "mapfile_queue_processor.py", line 41, in process_message
    cursor.execute(sql, args)
psycopg2.ProgrammingError: type "s" does not exist
LINE 2:             format('DATA "the_geom from ('%s') as subquery
                                                   ^

現在,我根據人們以前的建議嘗試了幾種不同的修復程序,但是都沒有用。

在sql變量中,我嘗試將所有%s設置為%%s'%s'以及'%%s'"%s"以及"%%s"甚至是{s}它的地獄

我似乎找到的唯一可能的解決方案是我不能有args = ('%s','%s','%s','%s','%s')並且我需要有實際的參數而不是'%s'

這是我的問題的解決方案嗎? 如果是這樣,我該怎么做?

如果不是解決方案,該如何解決?

cursor.execute()中的args參數應該是傳遞給查詢的實際參數(它們將代替%s占位符)。

cursor.execute()您的args應該包含要在查詢中替換的實際參數(值),而不是'%s'。 文檔中所述

Psycopg按類型將Python變量轉換為SQL文字。 許多標准的Python類型已經適應了正確的SQL表示形式。

示例:Python函數調用:

>>> cur.execute(
...     """INSERT INTO some_table (an_int, a_date, a_string)
...         VALUES (%s, %s, %s);""",
...     (10, datetime.date(2005, 11, 18), "O'Reilly"))

轉換為SQL命令:

INSERT INTO some_table (an_int, a_date, a_string)
 VALUES (10, '2005-11-18', 'O''Reilly');

使用%(name)的占位符也支持命名參數。 使用命名參數,可以按任何順序將值傳遞到查詢,並且許多占位符可以使用相同的值:

>>> cur.execute(
...     """INSERT INTO some_table (an_int, a_date, another_date, a_string)
...         VALUES (%(int)s, %(date)s, %(date)s, %(str)s);""",
...     {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})

我認為您不能使用參數綁定(即由psycopg處理的'%s')在引用的內部查詢中進行占位符替換。 您將必須自己構建一些查詢字符串,轉義要在查詢中逐字結尾的每個'%'。

sql = "select 'Hello, %s' from bobs where id = %%s" % ("Bob",)
cursor.execute( sql, [123] )

顯然,您需要清理參數-我認為psycopg為此提供了一些功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM