Python 用于批量插入的电子媒介。除非包中内置了自动转换器,否则这可能仍然是唯一的解决方案。同样对于PostGIS,WKB hex是加载和读取地理类型数据的首选方法。这不会关闭数据库连接。 # Imports import sqlalchemy as sal imp
Python 用于批量插入的电子媒介。除非包中内置了自动转换器,否则这可能仍然是唯一的解决方案。同样对于PostGIS,WKB hex是加载和读取地理类型数据的首选方法。这不会关闭数据库连接。 # Imports import sqlalchemy as sal imp,python,mysql,pandas,geopandas,Python,Mysql,Pandas,Geopandas,用于批量插入的电子媒介。除非包中内置了自动转换器,否则这可能仍然是唯一的解决方案。同样对于PostGIS,WKB hex是加载和读取地理类型数据的首选方法。这不会关闭数据库连接。 # Imports import sqlalchemy as sal import geopandas as gpd # Function to generate WKB hex def wkb_hexer(line): return line.wkb_hex # Convert `'geom'` colu
用于批量插入的电子媒介。除非包中内置了自动转换器,否则这可能仍然是唯一的解决方案。同样对于PostGIS,WKB hex是加载和读取地理类型数据的首选方法。这不会关闭数据库连接。
# Imports
import sqlalchemy as sal
import geopandas as gpd
# Function to generate WKB hex
def wkb_hexer(line):
return line.wkb_hex
# Convert `'geom'` column in GeoDataFrame `gdf` to hex
# Note that following this step, the GeoDataFrame is just a regular DataFrame
# because it does not have a geometry column anymore. Also note that
# it is assumed the `'geom'` column is correctly datatyped.
gdf['geom'] = gdf['geom'].apply(wkb_hexer)
# Create SQL connection engine
engine = sal.create_engine('postgresql://username:password@host:socket/database')
# Connect to database using a context manager
with engine.connect() as conn, conn.begin():
# Note use of regular Pandas `to_sql()` method.
gdf.to_sql(table_name, con=conn, schema=schema_name,
if_exists='append', index=False)
# Convert the `'geom'` column back to Geometry datatype, from text
sql = """ALTER TABLE schema_name.table_name
ALTER COLUMN geom TYPE Geometry(LINESTRING, <SRID>)
USING ST_SetSRID(geom::Geometry, <SRID>)"""
conn.execute(sql)
# Imports
from geoalchemy2 import Geometry, WKTElement
from sqlalchemy import *
# Use GeoAlchemy's WKTElement to create a geom with SRID
def create_wkt_element(geom):
return WKTElement(geom.wkt, srid = <your_SRID>)
geodataframe['geom'] = geodataframe['geom'].apply(create_wkt_element)
db_url = 'postgresql://username:password@host:socket/database'
engine = create_engine(db_url, echo=False)
# Use 'dtype' to specify column's type
# For the geom column, we will use GeoAlchemy's type 'Geometry'
your_geodataframe.to_sql(table_name, engine, if_exists='append', index=False,
dtype={'geom': Geometry('POINT', srid= <your_srid>)})
# Imports
from geoalchemy2 import Geometry, WKTElement
from sqlalchemy import *
geodataframe['geom'] = geodataframe['geom'].apply(lambda geom: WKTElement(geom.wkt, srid = <your_SRID>))
db_url = 'postgresql://username:password@host:socket/database'
engine = create_engine(db_url, echo=False)
# Use 'dtype' to specify column's type
# For the geom column, we will use GeoAlchemy's type 'Geometry'
your_geodataframe.to_sql(table_name, engine, if_exists='append', index=False,
dtype={'geom': Geometry('POINT', srid= <your_srid>)})