Leave a comment

Search and Update Cursors


There are three types of cursors that can be used in geoprocessing. The three types of cursors are Search, Insert and Update.  The most commonly used cursor is the Search Cursor.  The Search Cursor is used to run through a set of data to find values to make calculations on another set of data.  That is, a Search Cursor is read only and cannot be used to update or overwrite the original data.  The Insert Cursor is used to insert a new record into a table.  The Update Cursor is used to update values in a dataset.

I will show snippets for using the Update Cursor as well as the Search Cursor.

The Search Cursor

The Search Cursor can be used to read through a dataset and search for specific information that can then be written out or printed.  I recently used this to select values from a shapefile to write out to a .csv file.

 


## The geoprocessing command is gp.SearchCursor() and requires at least one argument.

cursor=gp.SearchCursor(Input) #Assuming that Input is a sys.argv[]

row=cursor.Next()
while row:
line=[]
for fld in header:
value=row.GetValue(fld)
line.append(value)
linewriter.writerow(line)
row=cursor.Next()

del cursor

So in this case i read through my input lines to write out to a .csv.  Obviously I performed other functions on the data prior to writing out my text file.  There are a multitude of uses for the Search Cursor and this is just one example.

The Update Cursor

An example of the use for an Update Cursor is an export process to a customer database that requires an updated date and time.  I have a customer table that gets exported and when it does I want it to update the current date and time.  Now there are a million ways to write an Update Cursor but this techniques works best for me.

 


## The geoprocessing command is gp.UpdateCursor() and requires at least one argument.

cursor=gp.UpdateCursor(Input) #Assuming that Input is a sys.argv[]

row=cursor.Next()

while row:
row.Updated = datetime.today().isoformat()
cursor.UpdateRow(row)
row = cursor.Next()

del cursor

This iterates through the “Input” and updates in each row the field Updated with the current date and time.  You must also have in the beginning of your script:

from datetime import datetime

I think that the biggest difference in the Update Cursor from the Search Cursor is that each iteration through the rows you must use UpdateRow to write the value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: