Inserting and updating rows inside an edit session

As I've mentioned throughout the chapter, inserts, updates, or deletes made to a table or feature class done outside an edit session are permanent. They can't be undone. Edit sessions give you much more flexibility to roll back any unwanted changes.

Getting ready

Up until now, we've used insert and update cursors to add, edit, and delete data from feature classes and tables. These changes are permanent as soon as the script is executed and can't be undone. The new Editor class in the data access module supports the ability to create edit sessions and operations. With edit sessions, changes applied to feature classes or tables are temporary until permanently applied with a specific method call. This is the same functionality provided by the Edit toolbar in ArcGIS for Desktop.

Edit sessions begin with a call to Editor.startEditing(), which initiates the session. Inside the session, you then start an operation with the Editor.startOperation() method. Within this operation, you then perform various operations that perform edits on your data. These edits can also be subject to undo, redo, and abort operations to roll back, roll forward, and abort your editing operations. After the operations have been completed, you then call the Editor.stopOperation() method followed by Editor.stopEditing(). Sessions can be ended without saving changes. In this event, changes are not permanently applied. An overview of this process is provided in the following screenshot:

Getting ready

Edit sessions can also be ended without saving changes. In this event, changes are not permanently applied. Edit sessions also allow for operations to be applied inside the session and then either applied permanently to the database or rolled back. Additionally, the Editor class also supports undo and redo operations.

The following code example shows the full edit session stack, including the creation of the Editor object, the beginning of an edit session and an operation, edits to the data (an insert operation in this case), stopping the operation, and finally, the end of the edit session by saving the data:

edit = arcpy.da.Editor('Database Connections/Portland.sde')
edit.startEditing(False)
edit.startOperation()
with arcpy.da.InsertCursor("Portland.jgp.schools",("SHAPE","Name")) as cursor:
  cursor.insertRow([(7642471.100, 686465.725), 'New School'])
edit.stopOperation()
edit.stopEditing(True)

The Editor class can be used with personal, file, and ArcSDE geodatabases. Also, sessions can also be started and stopped on versioned databases. You are limited to editing only a single workspace at a time, and this workspace is specified in the constructor of the Editor object simply by passing in a string that references the workspace. Once created, this Editor object then has access to all the methods to start, stop, and abort operations as well as perform undo and redo operations.

How to do it…

Follow these steps to wrap UpdateCursor inside an edit session:

  1. Open IDLE.
  2. Open the C:ArcpyBookCh8UpdateWildfires.py script and save it to a new script called C:ArcpyBookCh8EditSessionUpdateWildfires.py.
  3. We're going to make several alterations to this existing script that updates values in the CONFID_RATING field.
  4. Remove the following lines of code:
    arcpy.AddField_management("FireIncidents","CONFID_RATING", "TEXT","10")
    print("CONFID_RATING field added to FireIncidents")
  5. Create an instance of the Editor class and start an edit session. These lines of code should be placed inside the try block:
    edit = arcpy.da.Editor(r'C:ArcpyBookCh8WildfireDataWildlandFires.mdb')
    edit.startEditing(True)
  6. Alter the if statement so that it appears as follows:
    if row[0] > 40 and row[0] <= 60:
      row[1] = 'GOOD'
    elif row[0] > 60 and row[0] <= 85:
      row[1] = 'BETTER'
    else:
      row[1] = 'BEST'
  7. End the edit session and save the edits. Place this line of code just below the counter increment:
    edit.stopEditing(True)
  8. The entire script should appear as follows:
    import arcpy
    import os
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch8/WildfireData/WildlandFires.mdb"
    try:
      edit = arcpy.da.Editor(r'C:ArcpyBookCh8WildfireDataWildlandFires.mdb')
      edit.startEditing(True)
      with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE", "CONFID_RATING")) as cursor:
        cntr = 1
        for row in cursor:
          # update the confid_rating field
          if row[0] > 40 and row[0] <= 60:
            row[1] = 'GOOD'
          elif row[0] > 60 and row[0] <= 85:
            row[1] = 'BETTER'
          else:
            row[1] = 'BEST'
          cursor.updateRow(row)
          print("Record number " + str(cntr) + " updated")
          cntr = cntr + 1
      edit.stopEditing(True)
    except Exception as e:
      print(e.message)
  9. You can check your work by examining the C:ArcpyBookcodeCh8EditSessionUpdateWildfires.py solution file.
  10. Save and run the script to update 374 records.

How it works…

Edit operations should take place inside an edit session, which can be initiated with the Editor.startEditing() method. The startEditing() method takes two optional parameters including with_undo and multiuser_mode. The with_undo parameter accepts a Boolean value of true or false, with a default of true. This creates an undo/redo stack when set to true. The multiuser_mode parameter defaults to true. When it's false, you have full control of editing a nonversioned or versioned dataset. If your dataset is nonversioned and you use stopEditing(False), your edit will not be committed. Otherwise, if set to true, your edits will be committed. The Editor.stopEditing() method takes a single Boolean value of true or false, indicating whether changes should be saved or not. This defaults to true.

The Editor class supports undo and redo operations. We'll first look at undo operations. During an edit session, various edit operations can be applied. In the event that you need to undo a previous operation, a call to Editor.undoOperation() will remove the most recent edit operation in the stack. This is illustrated as follows:

How it works…

Redo operations, initiated by the Editor.redoOperation() method, will redo an operation that was previously undone. This is illustrated as follows:

How it works…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset