python - 将 mssql 空间字段导入 geopandas/shapely 几何图形

标签 python sql-server shapely geopandas

我似乎无法直接将 mssql 空间字段导入到 geopandas 中。我可以使用 Pymssql 将普通的 mssql 表导入 pandas,不会出现任何问题,但我无法找到将空间字段导入形状几何的方法。我知道 mssql 的 OGR 驱动程序应该能够处理它,但我在 sql 方面不够熟练,无法解决这个问题。 对于直线和多边形来说,这更是一个问题,因为点可以从 mssql 字段转换为 x 和 y 坐标。 谢谢!

最佳答案

我通过正确查询 sql 数据库表并通过 shapely.wkt 中的加载函数将 wkt 字符串转换为 shapely 几何图形来解决这个问题。

我不是程序员,因此在函数的组织中请记住这一点。该函数可以导入带有或不带有GIS几何图形的mssql表。

from pymssql import connect
from pandas import read_sql
from shapely.wkt import loads
from geopandas import GeoDataFrame

def rd_sql(server, database, table, col_names=None, where_col=None, where_val=None, geo_col=False, epsg=2193, export=False, path='save.csv'):
    """
    Imports data from MSSQL database, returns GeoDataFrame. Specific columns can be selected and specific queries within columns can be selected. Requires the pymssql package, which must be separately installed.
    Arguments:
    server -- The server name (str). e.g.: 'SQL2012PROD03'
    database -- The specific database within the server (str). e.g.: 'LowFlows'
    table -- The specific table within the database (str). e.g.: 'LowFlowSiteRestrictionDaily'
    col_names -- The column names that should be retrieved (list). e.g.: ['SiteID', 'BandNo', 'RecordNo']
    where_col -- The sql statement related to a specific column for selection (must be formated according to the example). e.g.: 'SnapshotType'
    where_val -- The WHERE query values for the where_col (list). e.g. ['value1', 'value2']
    geo_col -- Is there a geometry column in the table?
    epsg -- The coordinate system (int)
    export -- Should the data be exported
    path -- The path and csv name for the export if 'export' is True (str)
    """
    if col_names is None and where_col is None:
        stmt1 = 'SELECT * FROM ' + table
    elif where_col is None:
        stmt1 = 'SELECT ' + str(col_names).replace('\'', '"')[1:-1] + ' FROM ' + table
    else:
        stmt1 = 'SELECT ' + str(col_names).replace('\'', '"')[1:-1] + ' FROM ' + table + ' WHERE ' + str([where_col]).replace('\'', '"')[1:-1] + ' IN (' + str(where_val)[1:-1] + ')'
    conn = connect(server, database=database)
    df = read_sql(stmt1, conn)

    ## Read in geometry if required
    if geo_col:
        geo_col_stmt = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=" + "\'" + table + "\'" + " AND DATA_TYPE='geometry'"
        geo_col = str(read_sql(geo_col_stmt, conn).iloc[0,0])
        if where_col is None:
            stmt2 = 'SELECT ' + geo_col + '.STGeometryN(1).ToString()' + ' FROM ' + table
        else:
            stmt2 = 'SELECT ' + geo_col + '.STGeometryN(1).ToString()' + ' FROM ' + table + ' WHERE ' + str([where_col]).replace('\'', '"')[1:-1] + ' IN (' + str(where_val)[1:-1] + ')'
        df2 = read_sql(stmt2, conn)
        df2.columns = ['geometry']
        geometry = [loads(x) for x in df2.geometry]
        df = GeoDataFrame(df, geometry=geometry, crs={'init' :'epsg:' + str(epsg)})

    if export:
        df.to_csv(path, index=False)

    conn.close()
    return(df)

编辑:使函数自动查找几何字段(如果存在)。

关于python - 将 mssql 空间字段导入 geopandas/shapely 几何图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39971629/

相关文章:

python - 如何在 wxPython 中向 TextCtrl 小部件添加标题?

python - 如何只打印一个txt文件中的一行? (Python)

sql-server - 如何通过 Coldfusion HTML 表单优雅地将 Excel 文件导入 Sql Server?

python - 为什么输出不同?

python - 获取 DuplicateKeyError 的重复值

python - 如何使用 py(py)odbc 从 python 连接到远程 MS SQL Server

Sql 异常 '@errno' 附近语法不正确

python - 两条不相交线之间的角度

python - 如何在 pandas 或 GeoPandas 中过滤具有无效几何图形的 WKT 字符串

python - 在 basemap 上绘制填充多边形会引发 __getitem__ 错误