Search code examples
pythonsqlfunctionarcgis

Trouble inputting interger values into an SQL statement within ArcGIS


So I am defining a function for use in a ArcGIS tool that will verify attributes, catch errors, and obtain user input to rectify those error. I want the tool to select and zoom to the segment that is being currently assessed so that they can make an informed decision. This is what I have been using, and it works well. But the CONVWGID is the variable that will be changing, and I'm not sure how to input that variable into an SQL statement without causing errors.

This is how I had tested the logic:

def selectzoom():
    arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", " [CONVWGID] = 10000001")

    mxd = arcpy.mapping.MapDocument('CURRENT')
    df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
    df.zoomToSelectedFeatures()
    arcpy.RefreshActiveView()

Then I needed to work the variable into the function in order to accept different CONVWGID values, which gives me a Runtime/TypeError that I should have known would happen.

Runtime error - Traceback (most recent call last): - File "string", line 1, in module - TypeError: cannot concatenate 'str' and 'int' objects

def selectzoom(convwkgid):
    delimfield = '" [CONVWGID] = ' + convwkgid + ' "'
    arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", delimfield)

    mxd = arcpy.mapping.MapDocument('CURRENT')
    df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
    df.zoomToSelectedFeatures()
    arcpy.RefreshActiveView()

And when I alter the delimfield line to change the integer into a string, it selects all of the attributes in the entire feature class. Not just the one that had been passed via the function call.

delimfield = '"[CONVWGID] = ' + str(convwkgid) + '"'

I'm not amazing with SQL and maybe I'm missing something basic with this statement, but I can't figure out why it won't work when I'm basically giving it the same information:

"[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"'

Solution

  • It turned out to be the extra inclusion of Double quotes inside of my single quotes that raised this problem.

    Thanks to @Emil Brundage for the help!

    Let's say convwkgid = 10000001

    '"[CONVWGID] = ' + str(convwkgid) + '"' doesn't equal "[CONVWGID] = 10000001"
    
    '"[CONVWGID] = ' + str(convwkgid) + '"' would actually be '"CONVWGID] = 10000001"'
    

    Try instead:

    '[CONVWGID] = ' + str(convwkgid)