[英]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.