aprx.updateConnectionProperties() no hace nada.

282
10
Jump to solution
2 weeks ago
AnibalMmartinez
Frequent Contributor

El siguiente ejemplo que esta en la ayuda, no funciona para nada no pincha , no cambia nada.

import arcpy

aprx = arcpy.mp.ArcGISProject(r'C:\Projects\YosemiteNP\Yosemite.aprx')

aprx.updateConnectionProperties(None, r'C:\Projects\YosemiteNP\DBConnections\Server.sde')

aprx.saveACopy(r"C:\Projects\YosemiteNP\YosemiteNew.aprx")

¿Alguna idea?, tengo un monton de APRX, que apuntan a la GEODATABASE de desarrollo, y debo cambiar la conexion para pasar a TESTING o PRODUCCION.

Anibal Martinez

0 Kudos
1 Solution

Accepted Solutions
AnibalMmartinez
Frequent Contributor

Funciona, hasta el primer ejemplo 

import arcpy
aprx = arcpy.mp.ArcGISProject(r'D:\Repo\VRed\main\project\Scripts\Publicar\MiniTest.aprx')
result=aprx.updateConnectionProperties(r'D:\Repo\VRed\main\project\Conexiones\SDE@MUGISD.sde', r'D:\Repo\VRed\main\project\Conexiones\SDE@MUGIST.sde',False,False,True)
print(result)
aprx.saveACopy(r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTestNew.aprx")

Cambia perfecto la conexion en el APRX, sin esos 3 parametros no funciona. No me puse a ver cual de los 3 es el responsable. 

Gracias @TonyAlmeida , gracias @DanPatterson , por la ayuda, y espero les sirva a muchos, porque veo que hay mucha gente buscando solución a este tema.

View solution in original post

10 Replies
TonyAlmeida
MVP Regular Contributor

Intenta agregar ambas conexiones al SDE, la antigua y la nueva.

import arcpy

aprx = arcpy.mp.ArcGISProject(r"C:\Temp\Project.aprx")

old_conn = r"xyz\xyz\DEV.sde"
new_conn = r"xyz\xyz\PROD.sde"

# Conexiones al SDE, la antigua y la nueva
aprx.updateConnectionProperties(old_conn, new_conn)

aprx.saveACopy(r"C:\Temp\Project.aprx")

 

0 Kudos
AnibalMmartinez
Frequent Contributor

import arcpy

aprx = arcpy.mp.ArcGISProject(r'C:\Projects\YosemiteNP\Yosemite.aprx')

aprx.updateConnectionProperties(r'C:\Projects\YosemiteNP\DBConnections\Server.sde'r'C:\Projects\YosemiteNP\DBConnections\NewServer.sde')

aprx.saveACopy(r"C:\Projects\YosemiteNP\YosemiteNew.aprx")

Tony, Hice la prueba, y No hace nada.

0 Kudos
DanPatterson
MVP Esteemed Contributor

From your example, which is also in the help files, there is this line....

If no matches are found when you replace the current_connection_info parameter with the new_connection_info parameter in the updateConnectionProperties function, your script may complete, but nothing will be updated.

Updating and fixing data sources—ArcGIS Pro | Documentation

Perhaps you need to check with your data sources to see if they exist since it suggests that it won't update anything, and, there is no mention of it throwing an error message either.


... sort of retired...
0 Kudos
AnibalMmartinez
Frequent Contributor

Gracias Dan, las conexiones también creadas por script pyhton y por las dudas utilizadas con ArcGIS Pro, para verificar. La versión actual de ArcGIS Pro es 3.1.6 y ArcGIS Server 11.1. 

Es muy frustrante, en 10.9.1 los sctipts funcionaban, luego de migrar y adaptarlos, nada.

He levantado un ticket al distribuidor local, ojala ellos encuentren algo.

Saludos,

Anibal

0 Kudos
TonyAlmeida
MVP Regular Contributor

I tested the code I posted and it does work. Here is redefined code that will print out layers current connections to help.

import arcpy
import os

# Set your paths
project_path = "CURRENT"  # Or full path to your APRX file
old_gdb = r"C:\Temp\BuildingPermit.gdb"
new_gdb = r"C:\Temp\BPTest.gdb"

# Open the ArcGIS project
aprx = arcpy.mp.ArcGISProject(project_path)

# Iterate through each map in the project
for m in aprx.listMaps():
    for l in m.listLayers():
        if l.supports("CONNECTIONPROPERTIES"):
            try:
                # Get the current connection properties
                conProp = l.connectionProperties
                print(f"Layer: {l.name}, Current Database: {conProp['connection_info']['database']}")

                # Check if the layer is connected to the old geodatabase
                if conProp and 'connection_info' in conProp:
                    current_database = conProp['connection_info'].get('database', '')
                    if current_database.lower() == old_gdb.lower():
                        print(f"Updating connection for layer: {l.name}")
                        
                        # Update the database path to the new geodatabase
                        conProp['connection_info']['database'] = new_gdb
                        
                        # Apply the updated connection properties
                        l.updateConnectionProperties(l.connectionProperties, conProp)
                    else:
                        print(f"Layer {l.name} is not using the old GDB. Skipping...")
            except Exception as e:
                print(f"Error with layer {l.name}: {str(e)}")

# Save the updated project
aprx.saveACopy(r"C:\Temp\Project_Updated.aprx")
print("Update complete.")

 

0 Kudos
AnibalMmartinez
Frequent Contributor

Hola Tony, mil gracias por el aporte, hice un pequeño cambio para que no pinche, y mas abajo la salida, ¿se te ocurre que puede estar pasando?

import arcpy
import os

# Set your paths
project_path = r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTest.aprx" # Or full path to your APRX file
project_path_new=r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTestNew.aprx"
old_gdb = r"D:\Repo\VRed\main\project\Conexiones\SDE@MUGISD.sde"
new_gdb = r"D:\Repo\VRed\main\project\Conexiones\SDE@GISTECOD.sde"

# Open the ArcGIS project
aprx = arcpy.mp.ArcGISProject(project_path)
nroLys=0

# Iterate through each map in the project
for m in aprx.listMaps():
for l in m.listLayers():
nroLys=nroLys+1
print("layers nro=" + str(nroLys))
if l.supports("CONNECTIONPROPERTIES"):
try:
# Get the current connection properties
conProp = l.connectionProperties
print("conProp=" + str(conProp))
#comente la linea siguiente porque daba "Error with layer SDE.VIS_FC_EQ_HFC_LINEQ_V: 'database'"
#print(f"Layer: {l.name}, Current Database: {conProp['connection_info']['database']}")

# Check if the layer is connected to the old geodatabase
if conProp and 'connection_info' in conProp:
current_database = conProp['connection_info'].get('database', '')
if current_database.lower() == old_gdb.lower():
print(f"Updating connection for layer: {l.name}")

# Update the database path to the new geodatabase
conProp['connection_info']['database'] = new_gdb

# Apply the updated connection properties
l.updateConnectionProperties(l.connectionProperties, conProp)
else:
print(f"Layer {l.name} is not using the old GDB. Skipping...")
except Exception as e:
print(f"Error with layer {l.name}: {str(e)}")

# Save the updated project
aprx.saveACopy(project_path_new)
print("Update complete.")

 

SALIDA:

C:\Users\u194934>"C:\Program Files\ArcGIS\Pro\bin\Python\Scripts\propy.bat" D:\Repo\VRed\main\project\Scripts\Publicar\CS2.py
layers nro=1
conProp={'dataset': 'SDE.VIS_FC_EQ_HFC_LINEQ_V', 'workspace_factory': 'SDE', 'connection_info': {'authentication_mode': 'DBMS', 'dbclient': 'oracle', 'db_connection_properties': '192.168.244.71:1529/MUGISD', 'password': '<*********>', 'instance': 'sde:oracle$192.168.244.71:1529/MUGISD', 'server': '192.168.244.71', 'user': 'SDE', 'version': 'SDE.DEFAULT'}}
Layer SDE.VIS_FC_EQ_HFC_LINEQ_V is not using the old GDB. Skipping...
Update complete.

0 Kudos
TonyAlmeida
MVP Regular Contributor

From what I can see, your code is checking if layers are connected to old_gdb (a .sde file path), but the actual connection is an Oracle database (not a file path). I don't have oracle  but give this a try,

 

try,

import arcpy
import os

# Set your paths
project_path = "CURRENT"  # APRX file
old_gdb = r"C:\Temp\BuildingPermit.gdb"
new_gdb = r"C:\Temp\BPTest.gdb"

# Open the ArcGIS project
aprx = arcpy.mp.ArcGISProject(project_path)

# Iterate through each map in the project
for m in aprx.listMaps():
    for l in m.listLayers():
        if l.supports("CONNECTIONPROPERTIES"):
            try:
                # Get the current connection properties
                conProp = l.connectionProperties
                
                if conProp and 'connection_info' in conProp:
                    # Handle file geodatabase connections
                    if 'database' in conProp['connection_info']:
                        print(f"Layer: {l.name}, Current Database: {conProp['connection_info']['database']}")
                        if conProp['connection_info']['database'].lower() == old_gdb.lower():
                            print(f"Updating file GDB connection for layer: {l.name}")
                            conProp['connection_info']['database'] = new_gdb
                            l.updateConnectionProperties(l.connectionProperties, conProp)
                    
                    # Handle Oracle SDE connections
                    elif conProp['connection_info'].get('dbclient') == 'oracle':
                        instance = conProp['connection_info'].get('instance', '')
                        print(f"Layer: {l.name}, Oracle Instance: {instance}")
                        if "MUGISD" in instance.upper():
                            print(f"Updating Oracle connection for layer: {l.name}")
                            conProp['connection_info']['instance'] = instance.replace("MUGISD", "GISTECOD")
                            l.updateConnectionProperties(l.connectionProperties, conProp)
                    
                    else:
                        print(f"Layer {l.name} has unsupported connection type. Skipping...")
            
            except Exception as e:
                print(f"Error with layer {l.name}: {str(e)}")

# Save the updated project
aprx.saveACopy(r"C:\Temp\Project_Updated.aprx")
print("Update complete.")

 

0 Kudos
AnibalMmartinez
Frequent Contributor

Intente, Tony, nada hace nada.

Primer ejemplo: 

import arcpy
import os

# Set your paths
project_path = r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTest.aprx" # Or full path to your APRX file
project_path_new=r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTestNew.aprx"
old_gdb = r"D:\Repo\VRed\main\project\Conexiones\SDE@MUGISD.sde"
new_gdb = r"D:\Repo\VRed\main\project\Conexiones\SDE@GISTECOD.sde"

# Open the ArcGIS project
aprx = arcpy.mp.ArcGISProject(project_path)
nroLys=0

# Iterate through each map in the project
for m in aprx.listMaps():
for l in m.listLayers():
nroLys=nroLys+1
print("layers nro=" + str(nroLys))
if l.supports("CONNECTIONPROPERTIES"):
try:
# Get the current connection properties
conProp = l.connectionProperties
# Check if the layer is connected Oracle SDE connections
if conProp['connection_info'].get('dbclient') == 'oracle':
instance = conProp['connection_info'].get('instance', '')
print(f"Layer: {l.name}, Oracle Instance: {instance}")
if "MUGISD" in instance.upper():
print(f"Updating Oracle connection for layer: {l.name}")
conProp['connection_info']['instance'] = instance.replace("MUGISD", "GISTECOD")
print("old=" + str(l.connectionProperties['connection_info']['instance']))
result=l.updateConnectionProperties(l.connectionProperties, conProp)
conProp = l.connectionProperties
print("new=" + str(l.connectionProperties['connection_info']['instance']))
print(result)
else:
print(f"Layer {l.name} has unsupported connection type. Skipping...")
except Exception as e:
print(f"Error with layer {l.name}: {str(e)}")
# Save the updated project
aprx.saveACopy(project_path_new)
print("Update complete.")

SALIDA
C:\Users\u194934>"C:\Program Files\ArcGIS\Pro\bin\Python\Scripts\propy.bat" D:\Repo\VRed\main\project\Scripts\Publicar\CS2.py
layers nro=1
Layer: SDE.VIS_FC_EQ_HFC_LINEQ_V, Oracle Instance: sde:oracle$192.168.244.71:1529/MUGISD
Updating Oracle connection for layer: SDE.VIS_FC_EQ_HFC_LINEQ_V
old=sde:oracle$192.168.244.71:1529/MUGISD
new=sde:oracle$192.168.244.71:1529/MUGISD
None
Update complete.

 

Luego, lo simplifique, y tampoco nada graba, nada escribe en el aprx, ni da error.

import arcpy
import os

# Set your paths
project_path = r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTest.aprx" # Or full path to your APRX file
project_path_new=r"D:\Repo\VRed\main\project\Scripts\Publicar\MiniTestNew.aprx"
old_conex = {'connection_info': {'authentication_mode': 'DBMS', 'dbclient': 'oracle', 'db_connection_properties': '192.168.244.71:1529/MUGISD', 'password': '<*********>', 'instance': 'sde:oracle$192.168.244.71:1529/MUGISD', 'server': '192.168.244.71', 'user': 'SDE', 'version': 'SDE.DEFAULT'}}
new_conex = {'connection_info': {'authentication_mode': 'DBMS', 'dbclient': 'oracle', 'db_connection_properties': '192.168.244.77:1528/GISTECOD', 'password': '<*********>', 'instance': 'sde:oracle$192.168.244.77:1528/GISTECOD', 'server': '192.168.244.77', 'user': 'SDE', 'version': 'SDE.DEFAULT'}}

# Open the ArcGIS project
aprx = arcpy.mp.ArcGISProject(project_path)
aprx.updateConnectionProperties(old_conex,new_conex)
nroLys=0

# Iterate through each map in the project
for m in aprx.listMaps():
for l in m.listLayers():
nroLys=nroLys+1
print("layers nro=" + str(nroLys))
if l.supports("CONNECTIONPROPERTIES"):
print("old=" + str(l.connectionProperties['connection_info']['instance']))
result=l.updateConnectionProperties(old_conex, new_conex)
print(f"Updating Oracle connection for layer: {l.name}")
print("new=" + str(l.connectionProperties['connection_info']['instance']))
print(result)
else:
print(f"Layer {l.name} has unsupported connection type. Skipping...")

# Save the updated project
aprx.saveACopy(project_path_new)
print("Update complete.")


SALIDA
C:\Users\u194934>"C:\Program Files\ArcGIS\Pro\bin\Python\Scripts\propy.bat" D:\Repo\VRed\main\project\Scripts\Publicar\CS3.py
layers nro=1
old=sde:oracle$192.168.244.71:1529/MUGISD
Updating Oracle connection for layer: SDE.VIS_FC_EQ_HFC_LINEQ_V
new=sde:oracle$192.168.244.71:1529/MUGISD
None
Update complete.

Arcgis Pro 3.1.6 , Arcgis Server 11.1.0

0 Kudos
AnibalMmartinez
Frequent Contributor

Novedad!!!!

lyr.updateConnectionProperties(old, new)--> no hace nada, en todas las convinaciones que hicimos, pero ....

lyr.updateConnectionProperties(old, new,"",False)-- Graba!!!, modifica el lyr y luego de save, el aprx, voy a probar todo lo que hicimos con estos 2 parametros, que buscando que son:

updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})
auto_update_joins_and_relates
 

If set to True, the updateConnectionProperties method will also update the connections for associated joins or relates.

(The default value is True)

Boolean
validate
 

If set to True, the connection properties will only be updated if the new_connection_info value is a valid connection. If it is not valid, the connection will not be replaced. If set to False, the method will set all connections to match the new_connection_info value, regardless of a valid match. In this case, if a match does not exist, the data sources would be broken.

(The default value is True)

Boolean
ignore_case
 

Determines whether searches will be case sensitive. By default, queries are case sensitive. To perform queries that are not case sensitive, set ignore_case to True.

(The default value is False)

Boolean

 

También es raro que me tome el 3er parámetro "", segun la documentación de arcgis Pro 3.4 única online, estamos trabajando con 3.1.6

Es un avance, el aprx igual no anda, tira un signo de exclamación a la BD,  pero fue modificado.

0 Kudos