【问题标题】:How can I import a geoDataFrame to MySQL?如何将 geoDataFrame 导入 MySQL?
【发布时间】:2020-08-05 00:06:31
【问题描述】:

我有一个 geoDataFrame,其结构如下:

<class 'geopandas.geodataframe.GeoDataFrame'>
RangeIndex: 28 entries, 0 to 27
Data columns (total 3 columns):
 #   Column       Non-Null Count  Dtype   
---  ------       --------------  -----   
 0   Name         28 non-null     object  
 1   Description  28 non-null     object  
 2   geometry     28 non-null     geometry
dtypes: geometry(1), object(2)
memory usage: 800.0+ bytes

这是我的 df 的样子:

我正在尝试使用 gdf.to_sql 将其保存在 MySQL 数据库中,并且我的连接使用的是 SQLAlchemy 但我收到以下错误:AttributeError: 'GeometryDtype' 对象没有属性 'base'。

我一直在环顾四周,发现了这个solution,但我找不到正确的语法使其适用于 MySQL。

【问题讨论】:

    标签: python mysql gis geopandas


    【解决方案1】:

    在尝试了很多事情后,我注意到 to_sql 函数没有生成正确的 MySQL 语法以使其工作。同样,如果我将文本保持原样,则使用更改为 wkb 的方法,MySQL 仍然无法将该列识别为几何图形(请参见问题中的图片)。

    对我有用的是将几何字段更改为字符串并在 python 中对其进行更新,使其看起来像这样:

    之后,我继续使用下面的代码,将数据帧发送到 MySQL,然后更新表以设置几何列:

    regions.to_sql('pr_regions', con=conn, schema='eq_pr_db',
                   if_exists='replace', index=False)
    
    #add column type Polygon
    
    conn.execute('''ALTER TABLE `eq_pr_db`.`pr_regions` 
                    ADD COLUMN `geom` Polygon;''')
    
    #populate new column by applying the ST_GeomFromText function to transform the string to geometry type.
    
    conn.execute('''UPDATE `eq_pr_db`.`pr_regions`
                    SET geom =  ST_GeomFromText(geometry) ;''')
    

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2022-01-11
      • 2015-09-01
      • 2020-02-18
      相关资源
      最近更新 更多