<< Click to Display Table of Contents >>

 

SearchCursor

 

 

用來查詢feature Class 或table資料, 此方法會先從資料集中取得唯讀Cursor, 之後透過迴圈循環的方式, 逐一取得feature Class資料的row data, 再從row data中讀取每筆資料的屬性值, SearchCursor本身也可以加入特定查詢條件與排序條件,取得符合特定條件的資料,在進行讀取。

SearchCursor讀取資料的方法,一般為使用for迴圈或是while迴圈(while需搭配cursor.next()來使用),簡單範例如下

 

import sgpy

fc = "C:/temp/Line2.shp"

field = "prop2"

cursor = sgpy.SearchCursor(fc)

#透過迴圈,不斷取得每筆資料並讀取,直到取得最後一筆資料為止

for row in cursor:

   print(row.getValue(field))  #讀取每筆資料,特定欄位的屬性值

 

import sgpy

fc = "C:/temp/Line2.shp"

field = "prop2"

cursor = sgpy.SearchCursor(fc)

row = cursor.next()  #取得第一筆資料

while row:

   print(row.getValue(field))   #讀取第一筆資料,特定欄位的屬性值

   row = cursor.next()        #取得下一筆資料

 

語法:

SearchCursor (dataset, where_clause, spatial_reference, fields)

參數

說明

參數類型

datase

資料集,可以是feature class

shp檔或是geo檔案

字串

where_clause

(可給或不給)

查詢條件,用於篩選出符合特定條件的資料,作為查詢成果, 若不指定,則回傳所有的資料, 作為查詢成果

字串

fields

用於過濾查詢成果中的欄位資料

僅將特定欄位資料回傳給Cursor,若不指定,則回傳查詢成果中所有欄位資料

字串

回傳值

類型

說明

Cursor

Cursor物件,含有查詢成果,可透過迴圈取得查詢成果row data, 逐一查詢每筆資料的屬性值

 

範例1,查詢特定欄位:

import sgpy

#  Input: C:/temp/Line2.shp

#  Fields: prop1; prop2; prop3

#建立查詢用cursor物件,保留符合特定條件的查詢成果

rows = sgpy.SearchCursor("D:/temp/Line2.shp", where_clause="prop2 = 'abc'")

# 透過迴圈,逐一取得查詢成果中,每筆資料的屬性值

for row in rows:

   print("prop1: {0}, prop2: {1}, prop3: {2}".format(

       row.getValue("prop1"),

       row.getValue("prop2"),

       row.getValue("prop3")))

   del row

del rows

範例2, 取得圖形所有點座標:

import sgpy

#  Input: C:/temp/Line2.shp

#建立查詢用cursor物件,查詢圖形座標資料

rows = sgpy.SearchCursor("D:/temp/Line2.shp", where_clause="Geometry@")

# 透過迴圈,逐一取得查詢成果中,每筆資料的屬性值

for geom in rows:

   pt = geom.next()

while pt:

        print str(pt.X) + " " + str(pt.Y)

        pt = geom.next()

del row

del rows

 


©2015 Supergeo Technologies Inc. All rights reserved.