Thursday 23 June 2016

arcgis 10.2 - Getting values of last row in table with ArcPy/SearchCursor?


I would like to base my query on the last row of a table? I know the basic syntax/functionality for my search cursor, how do I query only the last row;



Below is an example of my search criteria, this data comes from a log of success/fail for a script that runs, I will base other decisions off of the success or fail later in the application.


How do I add to my existing code the function to look in the last row, to getValue of timeand success or fail


I am using ArcGIS 10.2.


cursor = arcpy.SearchCursor(aTable,"""Time > DATEADD(minute, -2,  GETDATE())""")
for row in cursor:
print(row.getValue("Time"))
if row.getValue("Time") < datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S'):
print "true"
else:
print "false"


This is later implemented in the script and creates the success or fail values as yes and norespectively.


rows = arcpy.InsertCursor(aTable)
for x in xrange(0, outputobjects):
row = rows.newRow()
row.setValue("Success", 'YES')
row.setValue("Fail", 'NO')
row.setValue("Time", Start)
rows.insertRow(row)

Answer




I would usually suggest the da.SearchCursor as well, but its order by clause only works withe data in a database. So, if it is in a database:


a_table = "YourTable"
order_fld = "Time"
return_flds = ["Time", "SomeOtherField"]
where_str = """Time > DATEADD(minute, -2, GETDATE())"""

sql_clause = (None,'ORDER BY {} DESC'.format(order_fld))

last_row = ''
last_time = ''

with arcpy.da.SearchCursor(a_table, return_flds, where_clause=where_str, sql_clause=sql_clause) as cursor:
last_row = cursor.next()
last_time = last_row[0]

Else, if it is a shapefile:


sort_string = "{} D".format(order_fld)
arcpy.SearchCursor(a_table, where_clause=where_str, sort_fields=sort_string)
last_row = cursor.next()
last_time = last_row.Time


Both of these, you don't have to loop through the entire result to get the "last" row. By ordering by descending, the last row is the 1st row, and you can move on.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...