使用场景:1.工作中经常需要将SDE库中的数据备份到GDB中,2.基于数据安全要时常手动去备份SDE数据库。
整个自动备份分为两个脚本:sde_bak.bat与sde_to_gdb.py。其中sde_to_gdb.py是进行数据备份的脚本。sde_bak.bat是执行sde_to_gdb.py脚本的定时任务。
创建sde_to_gdb.py脚本:
# -*- coding: utf-8 -*-
# Import arcpy module
import os
import arcpy
from arcpy import env
import time
import sys
if sys.getdefaultencoding() != 'gbk':
reload(sys)
sys.setdefaultencoding('gbk')
################################################################
#需要备份的空间库的用户名(只需将其中的TEST替换成对应的用户名,需要保留** 。*的格式
sdeuser='**TEST.*'
#备份生成gdb的名称
out_GDB_Name ='TEST'
#sde库的物理路径 arcgis中sde的连接地址
env.workspace = 'F:\\sde_copy\\Connection to localhost.sde'
################################################################
#如果要素重复直接覆盖
env.overwriteOutput = True
################################################################
#获取系统的年月日
yyMMdd = time.strftime('%Y%m%d', time.localtime(time.time()))
#获取系统的当前时间
hhmmss = time.strftime('%H%M%S', time.localtime(time.time()))
#构建gdb的绝对路径
out_GDB_Folder_Path = "F:\\sde_copy\\" + yyMMdd
out_GDB_Name = out_GDB_Name+'_'+hhmmss
#创建gdb目录
if not os.path.exists(out_GDB_Folder_Path):
os.mkdir(out_GDB_Folder_Path)
print('Directory Created')
#GDB文件路径
out_GDB_Path = out_GDB_Folder_Path + '\\' + out_GDB_Name + '.gdb'
print('GDB_Path:'+out_GDB_Path)
#################################################################################
#创建GDB文件
arcpy.CreateFileGDB_management(out_GDB_Folder_Path, out_GDB_Name, "CURRENT")
print('GDB Created')
#################################################################################
print("SDE_To_GDB Starting")
#################################################################################
#遍历要素类数据并进行拷贝
fclist = arcpy.ListFeatureClasses(sdeuser)
for fc in fclist:
print(fc)
basename = arcpy.Describe(fc).basename
outname =os.path.join(out_GDB_Path,basename.split('.')[1])
# outname = os.path.join(out_GDB_Path, basename)
str = basename.split('.')[1]
print(str + "_FeatureClass Copy Done")
arcpy.CopyFeatures_management(fc, outname)
#################################################################################
#遍历要素集及要素集中要素类并进行拷贝
dslist = arcpy.ListDatasets(sdeuser)
for ds in dslist:
dsname = arcpy.Describe(ds).basename
outdsname = os.path.join(out_GDB_Path, dsname.split('.')[1])
sr = arcpy.Describe(ds).SpatialReference
# outdsname = os.path.join(out_GDB_Path, dsname)
print(outdsname)
arcpy.CreateFeatureDataset_management(out_GDB_Path, dsname.split('.')[1],sr)
fclist = arcpy.ListFeatureClasses('','',dsname)
for fc in fclist:
basename = arcpy.Describe(fc).basename
outname = os.path.join(outdsname, basename.split('.')[1])
str = basename.split('.')[1]
print(str + "_FeatureClass Copy Done")
arcpy.CopyFeatures_management(fc, outname)
print('SDE_TO_GDB Done')
创建sde_bak.bat脚本
@echo off
:这里使用arcgis自带的python编辑器。
C:
cd C:\Python27\ArcGIS10.2
python F:\sde_copy\sde_to_gdb.py
sde_to_gdb.py脚本创建之后可以进行测试,cmd到arcgis自带的python安装目录文件夹下。
网友评论