Select to view content in your preferred language

updateConnectionProperties() is not working

1269
11
Jump to solution
09-28-2023 09:40 AM
NSamu
by
New Contributor III

Hello,

I am trying to update connection properties for all layers in a Pro project map that are connected to our admin database to a read-only version of that database. When I run the following script, it runs but the database connections do not get updated.

import arcpy
aprx = arcpy.mp.ArcGISProject("CURRENT")
for m in aprx.listMaps("Mobile_Map"):
for lyr in m.listLayers():
if not(lyr.isGroupLayer or lyr.isBasemapLayer):
try:
lyr.updateConnectionProperties(current_connection_info="A:\DBConnection\admin.sde", new_connection_info="A:\DBConnection\dr.sde")
except:
print("Not an sde database or the database connection does not need to be updated.")

Tags (3)
0 Kudos
11 Replies
BlakeTerhune
MVP Regular Contributor

Oh, glad you got it working!

As another suggestion, consider handling your exceptions a more specific, targeted manner. With your snippet, you will never know if there was some other problem with updateConnectionProperties() because you're printing a generic message for all exceptions. You need to know if something unexpected is happening, which your error handling will not show. I've started doing this as a pattern to add more information/context to errors.

import arcpy
aprx = arcpy.mp.ArcGISProject("CURRENT")
for m in aprx.listMaps("Mobile_Map"):
    for lyr in m.listLayers():
        if lyr.supports("connectionProperties"):
            try:
                print(lyr.connectionProperties["connection_info"])
                lyr_update = lyr.connectionProperties
                lyr_update['connection_info']['password']='<password>'
                lyr_update['connection_info']['user']='dr'
                lyr.updateConnectionProperties(lyr.connectionProperties, lyr_update)

            except Exception as e:
                raise Exception("Not an sde database or the database connection does not need to be updated.") from e
aprx.save()
del aprx

If you really want to pass on some specific error, you can handle that specifically. In this example, all arcpy errors will get passed and the code will continue running, but it will stop if the exception is not from arcpy (unhandled).

except arcpy.ExecuteError as arcpy_e:
    print(arcpy_e)
    print("Not an sde database or the database connection does not need to be updated.")
    pass
NSamu
by
New Contributor III

Thank you for this advice. Very helpful and much appreciated. 

0 Kudos