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})
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Oct 6, 2016 at 14:19
2
  • Try changing CountyNM = "Hamilton" to CountyNM = 'Hamilton' and then use the where_clause: 'CountyName = ' + CountyNM. Commented Oct 6, 2016 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. Commented Oct 6, 2016 at 14:27

1 Answer 1

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'
answered Oct 6, 2016 at 14:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.