2017-07-18 94 views
0

我想在SQLAlchemy中使用GeoPandas from_postgis功能时将参数传递给sql查询。SQLAlchemy传递参数与GeoPandas.from_postgis

类方法GeoDataFrame.from_postgis

我已经看过的先前相似(SQL,CON,geom_col = '的geom',CRS =无,index_col =无,coerce_float =真,则params =无) questionalso here,它建议使用SQLAlchemy的textual SQL选项。但是,这需要访问未包含在GeoDataFrame from_postgis选项中的con.execute。

你能否提出将参数传递给SQL的最佳方法?如果不是直接在from_postgis中,那么如何最好地单独构造完整的SQL字符串并将它作为第一个sql参数传递给from_postgis。

回答

2

对文本的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,如果这样更自然:

df.from_postgis(text("select * from foo where bar = :a"), params={"a": 1}) 

不要使用str.format作为其他答案的建议,因为它容易受到SQL注入的影响。

0

从联类似的问题:

sql= "select geom, x,y,z from your_table" 

我通常只是传递参数与字符串格式化:

sql_base = "select geom, x,y,z from your_table where x > {x}" 
sql = sql_base.format(x=some_x_value) 

一个限制是,你必须一次通过所有的参数,或者你会得到如果要设置多个参数,则为格式中的关键错误。