查询

属性查询

  1. from osgeo import ogr
  2. import os
  3. shpfile = r'C:\tmp\data.shp'
  4. ds = ogr.Open(shpfile)
  5. layer = ds.GetLayer(0) #得到图层
  6. lyr_count = layer.GetFeatureCount()
  7. print(lyr_count) #原先的要素总数
  8. layer.SetAttributeFilter("AREA > 800000") #属性查询条件
  9. lyr_count = layer.GetFeatureCount() #查询过后,layer被更新
  10. print(lyr_count) #满足条件的layer
  11. # 将该layer保存成shp
  12. driver = ogr.GetDriverByName("ESRI Shapefile")
  13. extfile = r'C:\tmp\data.shp'
  14. if os.access( extfile, os.F_OK ):
  15. driver.DeleteDataSource( extfile )
  16. newds = driver.CreateDataSource(extfile)
  17. layernew = newds.CreateLayer('rect',None,ogr.wkbPolygon)
  18. # 遍历,复制
  19. feat = layer.GetNextFeature()
  20. while feat is not None:
  21. layernew.CreateFeature(feat)
  22. feat = layer.GetNextFeature()
  23. newds.Destroy()

空间查询

SQL查询

  1. from osgeo import ogr
  2. driver = ogr.GetDriverByName("ESRI Shapefile")
  3. world_shp = r'C:\tmp\test.shp'
  4. world_ds = ogr.Open(world_shp)
  5. world_layer = world_ds.GetLayer()
  6. world_layer_name = world_layer.GetName()
  7. result = world_ds.ExecuteSQL("select * from %s where prov_id = '22' order by BNDRY_ID desc" % (world_layer_name)) # ) # ExecuteSQL是基于数据集进行的,而不是图层
  8. resultFeat = result.GetNextFeature ()
  9. out_shp = r'C:\tmp\test\test_sql_result.shp'
  10. create_shp_by_layer(out_shp, result) #保存结果
  11. # 对查询结果进行遍历
  12. while resultFeat :
  13. print resultFeat.GetField('BNDRY_ID')
  14. resultFeat = result.GetNextFeature ()
  15. #执行下一条SQL语句之前一定要先释放
  16. world_ds.ReleaseResultSet(result)