2

I know this is a very basic problem I should be able to solve myself, but I've had no luck. I have a variable I want to use in the query for arcpy.SelectLayerByAttribute, but the line that was working yesterday is now giving me an "error 000358: invalid expression". I simply want to use the variable CountyNM in the where clause.

Here is the section of code giving me issues:

CountyNM = "Hamilton"
arcpy.SelectLayerByAttribute_management("hzCountyLYR", "NEW_SELECTION", 'CountyName =' + "'"+ CountyNM +"'")

Syntax: SelectLayerByAttribute_management (in_layer_or_view, {selection_type}, {where_clause}, {invert_where_clause})
  • Try changing CountyNM = "Hamilton" to CountyNM = 'Hamilton' and then use the where_clause: 'CountyName = ' + CountyNM. – Joseph Oct 6 '16 at 14:25
  • depending on the type of gdb you are using it could be [CountyName] = ' Hamilton' , also instead of using CountyNM as a variable, I would make SQL a variable and send the entire SQL statement into it, then plug SQL as the where clause. – ed.hank Oct 6 '16 at 14:27
5

As you may not know where is your data stored, use arcpy.AddFieldDelimiters() which will handle the syntax for the field name.

import arcpy
input_gdb = r'C:\GIS\SanDiego.gdb'

CountyNM = "Hamilton"
field_name = arcpy.AddFieldDelimiters(input_gdb, 'CountyName')
where_clause = """ {} = '{}' """.format(field_name,CountyNM)
print where_clause
>>> CountyName = 'Hamilton'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.