1

I've been trying to write a stand alone script to run any query from python, but I've run into a few problems. At first I tried this:

fc = "U:\RealGDB.gdb\acutalLayerName" 
Where = """"TOTAL NUMB FLOORS" = 2""" #TOTAL NUMB FLOORS is the actual field name.
cursor = arcpy.da.SearchCursor(fc, ("'TOTAL NUMB FLOORS'"), Where)

for row in cursor: #python crashes here
    print (row[0])

This crashes python. I've spent about a week trying to fix this and I can safely say that I'm completely lost. Every time I change the sql format to something else - when I add some quotes or brackets - I get an invalid syntax error. What's wrong with my sql; why does it cause python to crash at my for loop?

I imported arcpy and os. The table has about 84.4 records.

5

The Defining fields in tables page in the Online Help (with my bolding) says:

Field names must also start with a letter and not contain spaces or reserved words.

There may be other issues too so try using a field which does not have spaces (like FLOORS) in its name and run this as a test:

fc = r"U:\RealGDB.gdb\acutalLayerName" 
where_clause = "FLOORS = 2"
with arcpy.da.SearchCursor(fc, ["FLOORS"], where_clause) as cursor:
    for row in cursor: 
        print row[0]

Some other things I did were:

  • renamed the variable from Where to where_clause - sometimes using a keyword (which Where may or may not be) can cause errors so I try to avoid them
  • used with syntax as illustrated in the arcpy.da cursor documentation. The advantages of this are I think documented there and in other Q&As here.
  • the structure of the where_clause is the simplest one that I know would do what you appeared to be trying to - they can get much more complex as illustrated in MANY Q&As here
  • Isn't that code the same thing as my code without spaces in the field name? Why did you choose to use a with clause? – user66821 Aug 2 '16 at 22:58
  • how did you know to use only one set of quotation marks in where_clause? Would you use more if this were a more complicated query? – user66821 Aug 4 '16 at 21:17
  • @Steve There are many correct and many incorrect ways to form where_clauses for use with ArcPy. In this case, which used a number/integer there is no need to surround the value with quotes like you would need to for a string, and there is no need to surround the field names with quotes, and so only one set of outer quotes is needed. – PolyGeo Aug 4 '16 at 22:50

Your Answer

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