mirror of
https://github.com/wassname/geopandas.git
synced 2026-09-09 11:22:50 +08:00
ENH: Use sqlalchemy for PostGIS connection for better compatibility with pandas.read_sql
This commit is contained in:
+1
-1
@@ -30,7 +30,7 @@ def read_postgis(sql, con, geom_col='geom', crs=None, index_col=None,
|
||||
index_col, coerce_float, params
|
||||
|
||||
"""
|
||||
df = read_sql(sql, con, index_col=index_col, coerce_float=coerce_float,
|
||||
df = read_sql(sql, con.engine, index_col=index_col, coerce_float=coerce_float,
|
||||
params=params)
|
||||
if geom_col not in df:
|
||||
raise ValueError("Query missing geometry column '{0}'".format(
|
||||
|
||||
+8
-7
@@ -1,6 +1,7 @@
|
||||
import io
|
||||
import os.path
|
||||
from six.moves.urllib.request import urlopen
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from geopandas import GeoDataFrame, GeoSeries
|
||||
|
||||
@@ -56,8 +57,11 @@ def validate_boro_df(test, df):
|
||||
|
||||
|
||||
def connect(dbname):
|
||||
driver = 'psycopg2'
|
||||
try:
|
||||
con = psycopg2.connect(dbname=dbname)
|
||||
conn_str = 'postgresql+{driver}://localhost/{dbname}'
|
||||
engine = create_engine(conn_str.format(driver=driver, dbname=dbname))
|
||||
con = engine.connect()
|
||||
except (NameError, OperationalError):
|
||||
return None
|
||||
|
||||
@@ -82,8 +86,7 @@ def create_db(df):
|
||||
return False
|
||||
|
||||
try:
|
||||
cursor = con.cursor()
|
||||
cursor.execute("DROP TABLE IF EXISTS nybb;")
|
||||
con.execute("DROP TABLE IF EXISTS nybb;")
|
||||
|
||||
sql = """CREATE TABLE nybb (
|
||||
geom geometry,
|
||||
@@ -92,20 +95,18 @@ def create_db(df):
|
||||
shape_leng float,
|
||||
shape_area float
|
||||
);"""
|
||||
cursor.execute(sql)
|
||||
con.execute(sql)
|
||||
|
||||
for i, row in df.iterrows():
|
||||
sql = """INSERT INTO nybb VALUES (
|
||||
ST_GeometryFromText(%s), %s, %s, %s, %s
|
||||
);"""
|
||||
cursor.execute(sql, (row['geometry'].wkt,
|
||||
con.execute(sql, (row['geometry'].wkt,
|
||||
row['BoroCode'],
|
||||
row['BoroName'],
|
||||
row['Shape_Leng'],
|
||||
row['Shape_Area']))
|
||||
finally:
|
||||
cursor.close()
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
return True
|
||||
|
||||
Reference in New Issue
Block a user