首页 > 解决方案 > psyco2.error.syntax 错误:输入末尾的语法错误)

问题描述

我正在尝试sql在 python 中运行查询。它确实在 中工作pgadmin,但 python 报告了语法错误。

cur_str.execute("select b2.linestring,b2.id,ST_Length(ST_Intersection(ST_Transform(ST_MakeValid(b2.linestring),28992),ST_Transform(ST
_MakeValid(b1.geom), 28992))) from public.ways b2, public.pc4_2017 b1 where ST_Intersects(ST_Transform(ST_MakeValid(b2.linestring),28992)
,ST_Transform(ST_MakeValid(b1.geom),28992)",([pc4]))
psycopg2.errors.SyntaxError: syntax error at end of input
LINE 1: ...linestring),28992),ST_Transform(ST_MakeValid(b1.geom),28992)
                                                                       ^

我能得到一些帮助吗?

标签: pythonsqlpsycopg2

解决方案


您需要使用三引号在 Python 中创建多行字符串:

cur_str.execute("""
    select 
        b2.linestring,
        b2.id,
        ST_Length(ST_Intersection(ST_Transform(ST_MakeValid(b2.linestring),28992), ST_Transform(ST_MakeValid(b1.geom), 28992)))
    from 
        public.ways b2, 
        public.pc4_2017 b1 
    where 
        ST_Intersects(ST_Transform(ST_MakeValid(b2.linestring),28992),ST_Transform(ST_MakeValid(b1.geom),28992))
    """, ([pc4]))

推荐阅读