SQLAlchemy 使用 GeoPandas.from_postgis 传递参数
SQLAlchemy pass parameters with GeoPandas.from_postgis
我想在将 GeoPandas from_postgis 功能与 SQLAlchemy 结合使用时将参数传递给 sql 查询。
classmethod GeoDataFrame.from_postgis(sql, con, geom_col='geom', crs=None, index_col=None, coerce_float=True, params=None)
我查看了之前类似的 and also here which suggests to use SQLAlchemy's textual SQL 选项。但是,这需要访问未包含在 GeoDataFrame from_postgis 选项中的 con.execute。
您能否建议将参数传递给 SQL 的最佳方法?如果不直接在 from_postgis 中,那么如何最好地单独构造完整的 SQL 字符串并将其作为第一个 sql 参数传递给 from_postgis.
对于文本 SQL,您可以使用 .bindparams
:
添加参数
query = text("select * from foo where bar = :a").bindparams(a=1)
对于您在 SQLAlchemy 中构建的查询,会自动包含绑定参数:
foo = Table(...) # you need to define foo
query = select(["*"]).select_from(foo).where(foo.c.bar == 1)
也可以直接通过from_postgis
的params
参数传参,如果这样更自然:
df.from_postgis(text("select * from foo where bar = :a"), params={"a": 1})
不要像其他答案建议的那样使用 str.format
,因为它容易受到 SQL 注入的攻击。
我想在将 GeoPandas from_postgis 功能与 SQLAlchemy 结合使用时将参数传递给 sql 查询。
classmethod GeoDataFrame.from_postgis(sql, con, geom_col='geom', crs=None, index_col=None, coerce_float=True, params=None)
我查看了之前类似的
您能否建议将参数传递给 SQL 的最佳方法?如果不直接在 from_postgis 中,那么如何最好地单独构造完整的 SQL 字符串并将其作为第一个 sql 参数传递给 from_postgis.
对于文本 SQL,您可以使用 .bindparams
:
query = text("select * from foo where bar = :a").bindparams(a=1)
对于您在 SQLAlchemy 中构建的查询,会自动包含绑定参数:
foo = Table(...) # you need to define foo
query = select(["*"]).select_from(foo).where(foo.c.bar == 1)
也可以直接通过from_postgis
的params
参数传参,如果这样更自然:
df.from_postgis(text("select * from foo where bar = :a"), params={"a": 1})
不要像其他答案建议的那样使用 str.format
,因为它容易受到 SQL 注入的攻击。