2017-07-18 100 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) 

一個限制是,你必須一次通過所有的參數,或者你會得到如果要設置多個參數,則爲格式中的關鍵錯誤。