Python将数据库表格(属性数据)转化为shp文件

环境

这里是在pycharm Python3 的环境中进行编写,连接的数据库是 SQL Server。这里给出一个Pycharm连接SQL Server 的教程。

其他的数据库也可以使用,主要使用对应数据库的查询语句获取到数据就行。

https://blog.csdn.net/m0_66722981/article/details/129792945

实现代码

def temp_shp(connect,out_path,table_name,query):
    #定义一个驱动
    driver = ogr.GetDriverByName("ESRI Shapefile")
    #wgs_84用于存储将图层设置为wgs_84的参数
    wgs_84 = osgeo.osr.SpatialReference()
    wgs_84.ImportFromEPSG(4326)
    #获取表的名称,设置输出路径
    shp_datasource = driver.CreateDataSource(out_path)
    #查询并获取信息
    cursor = connect.cursor(as_dict=True)
    cursor.execute(query)
    result = cursor.fetchall()
    if len(result) != 0:
    #创建一个新的图层:
        layer = shp_datasource.CreateLayer(table_name,wgs_84,geom_type=ogr.wkbPoint)
    #获取表格中的字段信息并创建属性
        for field in cursor.description:
            field_name = field[0]
            field_type = 2
    # 创建字段
            NewField = ogr.FieldDefn(field_name, ogr.OFTReal)
            NewField.SetPrecision(3)
            layer.CreateField(NewField)
    #根据查询结果去画图加属性
        for row in result :
            new_feature = ogr.Feature(layer.GetLayerDefn())
    # # # 添加几何形状
            longitude, latitude = float(row["long"]), float(row["lat"])
            point = ogr.Geometry(ogr.wkbPoint)
            point.AddPoint(longitude, latitude)
            new_feature.SetGeometry(point)
        # #添加属性
            Num = new_feature.GetFieldCount()
            data_value = list(row.values())
            for i in range(0, Num ):
                inputvalue = float(data_value[i])
                new_feature.SetField(i, inputvalue)
            layer.CreateFeature(new_feature)
            new_feature = None
    shp_datasource.Destory()
    

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值