#Name: Python ArcPy Connect to SDE and versions | |
#Author: Bryan McIntosh | |
#Description: An approach to connect to SDE, create a new version, and change | |
# to the new version - inside a python script. | |
import arcpy, datetime, os, tempfile, shutil | |
#Create a string of the date to append to version name (to keep unique) | |
now = datetime.datetime.now() | |
strDate = str(now.year) + str(now.month) + str(now.day) + str(now.hour) + str(now.minute) + str(now.second) | |
#Create a temp directory using tempfile module to store SDE connection files | |
sdeTempPath = tempfile.mkdtemp() | |
#Setup first SDE Connection | |
arcpy.CreateDatabaseConnection_management(sdeTempPath,'ConnName.sde','SQL_SERVER','db\\instance','OPERATING_SYSTEM_AUTH','#', '#', '#','DBName') | |
##Create a new version (default as parent version) | |
sdeVersionName = 'MyVersion_' + strDate | |
arcpy.CreateVersion_management(sdeTempPath + os.sep + 'ConnName.sde', 'prefixName.DEFAULT', sdeVersionName, 'PUBLIC') | |
#The prefix of the version name isn't known (based on user), so need to find it so we can connect later | |
sdeVersionNameFULL = '' | |
for version in arcpy.da.ListVersions(sdeTempPath + os.sep + 'ConnName.sde'): | |
if version.name.split('.')[1] == sdeVersionName and not version.children: | |
sdeVersionNameFULL = version.name.split('.')[0] + '.' + sdeVersionName | |
arcpy.AddMessage('Version verified: ' + sdeVersionNameFULL) | |
##Create new connection file pointing to the new version | |
arcpy.CreateDatabaseConnection_management(sdeTempPath,'ConnVersion.sde','SQL_SERVER','db\\instance','OPERATING_SYSTEM_AUTH','#', '#', '#','DBName','#','#', sdeVersionNameFULL) | |
##DO STUFF WITH THE NEW VERSION | |
##DO STUFF WITH THE NEW VERSION | |
##When done, Remove the temp path containing connection files | |
shutil.rmtree(sdeTempPath) |