One thing that makes writing WHERE clauses a lot easier is to use the AddFieldDelimiters
function, which automatically adds the correct, DBMS-specific delimiters for field identifiers, such as double-quotes for FGDB and brackets for PGDB.
The other thing you have to consider is whether the value is a number, string, or other data type. Specifically, strings are wrapped in single quotes while numbers are not. You could check the field type and add single quotes if it is a string field.
E.g.:
import arcpy
def buildWhereClause(table, field, value):
"""Constructs a SQL WHERE clause to select rows having the specified value
within a given field and table."""
# Add DBMS-specific field delimiters
fieldDelimited = arcpy.AddFieldDelimiters(table, field)
# Determine field type
fieldType = arcpy.ListFields(table, field)[0].type
# Add single-quotes for string field values
if str(fieldType) == 'String':
value = "'%s'" % value
# Format WHERE clause
whereClause = "%s = %s" % (fieldDelimited, value)
return whereClause
if __name__ == "__main__":
inputfc = r"C:\input.shp"
outputfc = r"C:\output.shp"
fieldname = "StudyID"
fieldvalue = 101
whereclause = buildWhereClause(inputfc, fieldname, fieldvalue)
arcpy.Select_analysis(inputfc, outputfc, whereclause)
See also the function in this answer for a multi-value version of the above function.
If you need to insert a variable inside of a string, the easiest (and preferred way) is to use str.format().
x,y,z = 1,2,3
print "{0} + {1} = {2}".format(x,y,z)
The result is the string "1 + 2 = 3". The brackets (and numbers inside of them) are used to refer to the parameter values passed to format().
So, in your instance, you'll want something like:
"\"DATE\" = date '{0}'".format(currentRaster)
Best Answer
Proper Python error checking using try catch should at least allow you to prevent a crash.
Apart from that, ArcPy offers the ValidateTableName and ValidateFieldName methods to do basic checks that can be used in code to possibly catch such errors, but note these tools DO NOT check for existing tables and fields, but allow you to test if a new supplied table or field name is valid in the context of the given geodatabase environment.
See this ArcGIS Help topic: Validating table and field names in Python
In case of the ValidateTableName method, you can see it actually modifies a supplied name to be valid, so in order to catch a mispelled table name, you would need to test the output of the method against the supplied table name. Again: this option doesn't check for existing tables and field names!
In order to test for the true presence of existing tables and fields, you could use the
arcpy.ListFeatureClasses
arcpy.ListTables
and
arcpy.ListFields
to do basic checks for validity.