[GIS] Are Database Connections the best way to access Feature Classes

arcgis-10.1arcpy

I wrote some code on my machine, debugged, tested… it works great. Now, a coworker wants to use my scripts. The problem, I used database connections to reference the database and feature classes and everyone names their database connections in a slightly different way. Is there a better way to reference the SDE database and features classes?

Here's how I reference the objects.

outputFC = "Database Connections/XXX_YYY_PROD.sde/Schema.FeatureClass" 

I did declare variables to contain the connection string but nonetheless someone still needs to change the script, even if it's only in one place. Is there a way to reference the database directly?

Best Answer

Using python you can get the directory of the code file you are executing. Therefore you can put sde connection file and your python code file in the same folder and share the folder with your friends (Per mr.adam suggestion)

sde_connection_file = "XXX_YYY_PROD.sde"
currentDir = os.path.dirname(os.path.realpath(__file__))
sdeConnFullPath = os.path.join(currentDir,sde_connection_file)
featureClass = "Schema.FeatureClass"
featureClassPath = os.path.join(sdeConnFullPath,featureClass)

Another option is to use CreateDatabaseConnection_management tool to create sde connection file in your code and then consume it.

import arcpy
arcpy.CreateDatabaseConnection_management("Database Connections",
                                          "utah.sde",
                                          "SQL_SERVER",
                                          "utah",
                                          "DATABASE_AUTH",
                                          "gdb",
                                          "gdb",
                                          "SAVE_USERNAME",
                                          "garfield",
                                          "#",
                                          "TRANSACTIONAL",
                                          "sde.DEFAULT")
Related Question