??ArcPy 游標(biāo)位于數(shù)據(jù)訪問模塊 (arcpy.da)中秕豫,包括用于查詢的 SearchCursor 宁否,插入數(shù)據(jù)的 InsertCursor ,更新和刪除的 UpdateCursor 复濒。
??SearchCursor 和 UpdateCursor 都支持 SQL WHERE 子句惭聂,用于限制所返回的記錄的可選表達(dá)式。在使用 SQL WHERE 子句時(shí)可以用 AddFieldDelimiters 函數(shù)返回字段分隔符,因?yàn)樗樵償?shù)據(jù)的格式不同咱筛,字段分隔符不同搓幌,如,文件地理數(shù)據(jù)庫和 shapefile 使用雙引號(hào) (" ")迅箩,個(gè)人地理數(shù)據(jù)庫使用方括號(hào) ([ ])溉愁,而 ArcSDE 地理數(shù)據(jù)庫不使用字段分隔符。
??使用游標(biāo)會(huì)鎖定處理的數(shù)據(jù)饲趋,使用完后需要釋放拐揭,可以使用 Python 的 with 語句,這會(huì)自動(dòng)釋放鎖奕塑。
SearchCursor
# -*- coding: utf-8 -*-
import arcpy
from arcpy import env
env.workspace = r'E:\EsriPress\Python\Data\Exercise07'
fc = 'airports.shp'
delimitedField = arcpy.AddFieldDelimiters(fc, 'COUNTY')
with arcpy.da.SearchCursor(fc, ('NAME', 'FIPS'), delimitedField + ' = \'Anchorage Borough\'') as cursor:
for row in sorted(cursor):
print("name:{0},county:{1}".format(row[0], row[1]))
InsertCursor
# -*- coding: utf-8 -*-
import arcpy
from arcpy import env
env.workspace = r'E:\EsriPress\Python\Data\Exercise07'
fc = 'Results/airports_anchorage.shp'
with arcpy.da.InsertCursor(fc, ('SHAPE@XY', 'Name')) as cursor:
cursor.insertRow(((-149.771939, 61.100004), 'New Airport'))
UpdateCursor
# -*- coding: utf-8 -*-
import arcpy
from arcpy import env
env.workspace = r'E:\EsriPress\Python\Data\Exercise07'
fc = 'Results/airports_anchorage.shp'
delimfield = arcpy.AddFieldDelimiters(fc, 'STATE')
with arcpy.da.UpdateCursor(fc, ('STATE', 'NAME'), delimfield + ' <> \'AK\'') as cursor:
for row in cursor:
row[0] = 'AK'
cursor.updateRow(row)
if row[1] == 'New Airport':
cursor.deleteRow()