Using ArcPy and on the same script, I would like to perform a SelectLayerByAttribute tool to select the features created with the InsertCursor tool.
coords = [1, 2, 3, 4]
pointlyr = 'point'
Sr = arcpy.spatialReference(4326)
Points = [arcpy.PointGeometry(arcpy.Point(coords[0], coords[1]), sr), arcpy.PointGeometry(arcpy.Point(coords[2], coords[3]), sr)]
ids = []
with arcpy.da.InsertCursor(pointlyr, "SHAPE@") as cursor:
for pt in Points:
cursor.insertRow([pt])
id = max(set(str(for i in arcpy.da.SearchCursor(pointlyr, "OBJECTID")))
ids.append(id)
query = f"OBJECTID IN {str(tuple(ids))}"
arcpy.SelectLayerByAttributes(pointlyr, "NEW_SELECTION", query)
However, the attribute table does not refresh and it gives me an error message of invalid query. The SearchCursor tool allows me to query the newly created records programmatically however I want the records to be selected on the map extent and attribute table. How can I overcome this issue?
Update Error message attached. Invalid expression error
2 Answers 2
The InsertCursor - ArcGIS Pro | Documentation returns an object, specifically an integer representing the ObjectID of the record that was just inserted, so all you have to do is store those integers.
coords = [1, 2, 3, 4]
pointlyr = 'point'
Sr = arcpy.spatialReference(4326)
Points = [arcpy.PointGeometry(arcpy.Point(coords[0], coords[1]), sr), arcpy.PointGeometry(arcpy.Point(coords[2], coords[3]), sr)]
with arcpy.da.InsertCursor(pointlyr, "SHAPE@") as cursor:
ids = [cursor.insertRow([pt]) for pt in Points]
query = f"OBJECTID IN ({','.join(str(id) for id in ids)})"
arcpy.management.SelectLayerByAttribute('pointlyr', "NEW_SELECTION", query)
As convenient as str(tuple(ids))
is, it will generate invalid SQL if there is only a single item in the list, so you should go with something different like ','.join(str(id) for id in ids)
.
Also, the tool is SelectLayerByAttribute
, no 's', and it resides in the arcpy.management
submodule. You will get an error if you try to call it from the arcpy
module.
The issue is with this line which makes no sense and you don't need it:
id = max(set(str(for i in arcpy.da.SearchCursor(pointlyr, "OBJECTID")))
It appears you are trying to store the object ID of the row created by the insert cursor. If you read the help file on the insertRow method of an insert cursor, insert what it returns into your list.
-
The code here gives me the most recent OBJECTID created. The issue remains where the newly created records cannot be selected on the map.user206005– user2060052023年11月03日 23:32:32 +00:00Commented Nov 3, 2023 at 23:32
Explore related questions
See similar questions with these tags.
with
with an old-style non-DA cursor, and can't read the contents until it is flushed.