cursor.insert row error

6725
7
Jump to solution
02-13-2014 12:22 PM
TonyAlmeida
Occasional Contributor II
I am trying to run a script as a tool but i get an error on cursor.insertRow(row) and i don't know why.
Could someone help me out please?

Error.
Traceback (most recent call last):   File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 45, in onMouseDownMap     cursor.insertRow(row) RuntimeError: Objects in this class cannot be updated outside an edit session [TonyTwoWay.DBO.TT]


code i am trying to run
import arcpy import pythonaddins import os from arcpy import env  class Add_points(object):     """Implementation for AddPoints_addin.Add_points (Tool)"""     def __init__(self):         self.enabled = True         self.cursor = 3 # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.     def onMouseDownMap(self, x, y, button, shift):          fc = "TonyTwoWay.DBO.TT"         workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"         arcpy.env.overwriteOutput = True          # Start an edit session. Must provide the worksapce.         edit = arcpy.da.Editor(env.workspace)          # Edit session is started without an undo/redo stack for versioned data         #  (for second argument, use False for unversioned data)         edit.startEditing(True)          # Start an edit operation         edit.startOperation()          list = []         with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:             for row in cursor:                 try:                     if "CC" in row[0]:                         list.append(int(row[0].strip("CC")))                    except TypeError:                     pass                 del cursor          list.sort()         AddressID = list[-1] + 1         AddressID = 'CC' + str(AddressID)          row_values = [(x, y, (x, y), AddressID)]         cursor = arcpy.da.InsertCursor(fc, ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"])          for row in row_values:             cursor.insertRow(row)         del cursor          arcpy.RefreshActiveView()                  # Stop the edit operation.         edit.stopOperation()          # Stop the edit session and save the changes         edit.stopEditing(True)                 pass
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
RichardFairhurst
MVP Honored Contributor
Do this:

workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
edit = arcpy.da.Editor(workspace)

Don't ever mix a script variable and an environment variable.  They are separate things.  Either prefix both with env. or don't prefix either with env.  There is a problem with your workspace connection string.  It must be invalid.  The second code you tried ignored the bad workspace string entirely, which is why it did not give the cannot open workspace error.

For the second code you never set the environment workspace.  The workspace it opens is the default environment workspace, which is not your connection string.  The default environment workspace is valid so it won't produce the cannot open workspace error, but the default workspace is not the workspace where your feature class is located.  Since the correct workspace where the feature class is located never actually got opened for editing the second error occurs.

And of course make sure the workspace connection string is correct including the path.  Use Modelbuilder to create a model where you set the environment path using the connection you have created and then export the model to a python script to see exactly the right syntax and connection string for setting up your workspace.  Drop the Feature Class into the model as well to see how it is named by the model including its path.  Then feed the workspace variable the model creates to the editor in the exported script.  You should not get a workspace cannot be opened error snce ModelBuilder will make sure the connection set up is fully validated.

View solution in original post

0 Kudos
7 Replies
RichardFairhurst
MVP Honored Contributor
See the InsertCursor help for how to use an insertcursor. You cannot specify a field list with an insertcursor.  Your field list is being interpreted as a Spatial Reference. You also can't insert a list object as the equivalent of a row using an Insert Cursor.  You have to create a real row object from the cursor and assign its individual fields from your list object and then insert the real row object with the insert cursor:

        row_values = [(x, y, (x, y), AddressID)]
        cursor = arcpy.da.InsertCursor(fc)

        for x in row_values:
            row = cursor.newRow()
            row.setValue("YourField", x(0)) # Fix to match your list values
            cursor.insertRow(row)
        del cursor
0 Kudos
TonyAlmeida
Occasional Contributor II
Thank you for your reply.

row.setValue("YourField", x(0)) # Fix to match your list values
do you men replace "YourField" with "X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"

I have tried the following with errors.
row_values = [(x, y, (x, y), AddressID)]
        cursor = arcpy.da.InsertCursor(fc, ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"])

        field_names = ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"]
        
        for x in row_values:
            row = cursor.newRow()
            row.setValue(field_names, x(0)) # Fix to match your list values
            cursor.insertRow(row)
        del cursor

Error
>>> 
Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 47, in onMouseDownMap
    row = cursor.newRow()
AttributeError: 'da.InsertCursor' object has no attribute 'newRow'
>>> 
0 Kudos
Luke_Pinner
MVP Regular Contributor
See the InsertCursor help for how to use an insertcursor. You cannot specify a field list with an insertcursor.


You're confusing an arcpy.InsertCursor with arcpy.da.InsertCursor - this is the correct help topic.
0 Kudos
RichardFairhurst
MVP Honored Contributor
Sorry about that.  The help system mislead me.  I thought I was looking at the da.InsertCursor and not the old InsertCursor.  So disregard the original comments.  Here is the correct help for the da.InsertCursor.  So you do use a field list and you should be able to insert a list object.

So returning to your original code and error.  Use the help here for the crucial steps in setting up an sde edit session.   I would especially look at Editor Example 2 at the bottom.
 
You might need to set a specific version for editing on your data, unless your sure that your input layer has the correct version.  For example:

# Process: Change Version
arcpy.ChangeVersion_management(ACCESS_OPENING_Layer, "TRANSACTIONAL", "ARG.ARG_PARENT", "")

I think your problem in starting the edit session is that in one place you set a variable called workspace to your workspace path, but then you actually start the edit session on the environment workspace and not the workspace path in your workspace variable.  Change this line from this:

        edit = arcpy.da.Editor(env.workspace)

to this:

        edit = arcpy.da.Editor(workspace)


Or else use the environment workspace this way:

        arcpy.env.workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
        edit = arcpy.da.Editor(arcpy.env.workspace)

I am trying to run a script as a tool but i get an error on cursor.insertRow(row) and i don't know why.
Could someone help me out please?

Error.
Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 45, in onMouseDownMap
    cursor.insertRow(row)
RuntimeError: Objects in this class cannot be updated outside an edit session [TonyTwoWay.DBO.TT]


code i am trying to run
import arcpy
import pythonaddins
import os
from arcpy import env

class Add_points(object):
    """Implementation for AddPoints_addin.Add_points (Tool)"""
    def __init__(self):
        self.enabled = True
        self.cursor = 3 # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.
    def onMouseDownMap(self, x, y, button, shift):

        fc = "TonyTwoWay.DBO.TT"
        workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
        arcpy.env.overwriteOutput = True

        # Start an edit session. Must provide the worksapce.
        edit = arcpy.da.Editor(env.workspace)

        # Edit session is started without an undo/redo stack for versioned data
        #  (for second argument, use False for unversioned data)
        edit.startEditing(True)

        # Start an edit operation
        edit.startOperation()

        list = []
        with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:
            for row in cursor:
                try:
                    if "CC" in row[0]:
                        list.append(int(row[0].strip("CC")))   
                except TypeError:
                    pass        
        del cursor

        list.sort()
        AddressID = list[-1] + 1
        AddressID = 'CC' + str(AddressID)

        row_values = [(x, y, (x, y), AddressID)]
        cursor = arcpy.da.InsertCursor(fc, ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"])

        for row in row_values:
            cursor.insertRow(row)
        del cursor

        arcpy.RefreshActiveView()
        
        # Stop the edit operation.
        edit.stopOperation()

        # Stop the edit session and save the changes
        edit.stopEditing(True)        
        pass
0 Kudos
TonyAlmeida
Occasional Contributor II
with
arcpy.env.workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
edit = arcpy.da.Editor(arcpy.env.workspace) i get the following error.

Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 18, in onMouseDownMap
    edit = arcpy.da.Editor(arcpy.env.workspace)
RuntimeError: cannot open workspace


but with 
workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
edit = arcpy.da.Editor(arcpy.env.workspace)

i get passed the runtimeError :cannot open workspace
but i get this error:
Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 45, in onMouseDownMap
    cursor.insertRow(row)
RuntimeError: Objects in this class cannot be updated outside an edit session [TonyTwoWay.DBO.TT]


So i am super confused on if i set arcpy.da.Editor to (arcpy.env.workspace) but use workspace instead of arcpy.env.workspace i can get passed the RuntimeError: cannot open workspace.

I believe i have the code correct to start an edit session.
I have include the arcpy.ChangeVersion_management but it's still giving me the same error
edit = arcpy.da.Editor(workspace)
RuntimeError: cannot open workspace

import arcpy
import pythonaddins
import os
from arcpy import env

class Add_points(object):
    """Implementation for AddPoints_addin.Add_points (Tool)"""
    def __init__(self):
        self.enabled = True
        self.cursor = 3 # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.
    def onMouseDownMap(self, x, y, button, shift):

        fc = "TonyTwoWay.DBO.TT"
        arcpy.env.workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
        arcpy.env.overwriteOutput = True
        arcpy.ChangeVersion_management('TonyTwoWay.DBO.TT','TRANSACTIONAL','dbo.DEFAULT', "")
        # Start an edit session. Must provide the worksapce.
        edit = arcpy.da.Editor(arcpy.env.workspace)

        # Edit session is started without an undo/redo stack for versioned data
        #  (for second argument, use False for unversioned data)
        edit.startEditing(False, True)

        # Start an edit operation
        edit.startOperation()

        list = []
        with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:
            for row in cursor:
                try:
                    if "CC" in row[0]:
                        list.append(int(row[0].strip("CC")))   
                except TypeError:
                    pass        
        del cursor

        list.sort()
        AddressID = list[-1] + 1
        AddressID = 'CC' + str(AddressID)

        row_values = [(x, y, (x, y), AddressID)]
        cursor = arcpy.da.InsertCursor(fc, ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"])

        for row in row_values:
            cursor.insertRow(row)
        del cursor
        del cursor

        arcpy.RefreshActiveView()
        
        # Stop the edit operation.
        edit.stopOperation()

        # Stop the edit session and save the changes
        edit.stopEditing(True)        
        pass
0 Kudos
RichardFairhurst
MVP Honored Contributor
Do this:

workspace = r"Database Servers\DSD15_SQLEXPRESS.sde"
edit = arcpy.da.Editor(workspace)

Don't ever mix a script variable and an environment variable.  They are separate things.  Either prefix both with env. or don't prefix either with env.  There is a problem with your workspace connection string.  It must be invalid.  The second code you tried ignored the bad workspace string entirely, which is why it did not give the cannot open workspace error.

For the second code you never set the environment workspace.  The workspace it opens is the default environment workspace, which is not your connection string.  The default environment workspace is valid so it won't produce the cannot open workspace error, but the default workspace is not the workspace where your feature class is located.  Since the correct workspace where the feature class is located never actually got opened for editing the second error occurs.

And of course make sure the workspace connection string is correct including the path.  Use Modelbuilder to create a model where you set the environment path using the connection you have created and then export the model to a python script to see exactly the right syntax and connection string for setting up your workspace.  Drop the Feature Class into the model as well to see how it is named by the model including its path.  Then feed the workspace variable the model creates to the editor in the exported script.  You should not get a workspace cannot be opened error snce ModelBuilder will make sure the connection set up is fully validated.
0 Kudos
TonyAlmeida
Occasional Contributor II
In another one of my posts i ask about workspace and JSkinns indicatted that i need to creat a connection file.

His instrucitons;
Right-click on your SQL Server Express database > Save Connection. This will save it as an SDE connection file under "Database Connections". Then set your workspace to this .sde connection file.

so in ArcCatalog i right-clicked on the newly created connection from the instructions above, selected properties and in the Gerneral tab, Name: there is the complete path to the Connection file.

I used this in my workspace and it worked!
working code.
fc = "TonyTwoWay.DBO.TT"
workspace = r"C:\Users\talmeida\AppData\Roaming\ESRI\Desktop10.1\ArcCatalog\Connection to dsd15_sqlexpress.sde"

# Start an edit session. Must provide the worksapce.
edit = arcpy.da.Editor(workspace)


Thanks for your help rfairhur24.
0 Kudos