为在 SQL Server 中创建数据库和地理数据库 (geodatabase) 编写脚本

您可以复制并修改下方所提供的示例脚本之一。其中一个脚本是在 Microsoft SQL Server 实例中同时创建数据库和地理数据库。另外一个脚本在现有预配置 SQL Server 数据库中创建地理数据库。

在运行脚本之前必须完成一些附加任务。以下步骤对这些任务和脚本自身进行了介绍:

步骤:
  1. 在服务器上安装并配置 SQL Server
  2. 确保 SQL Server 实例可接受连接(例如确保服务正在运行且通信协议已启用)。
  3. 如果要从安装有 SQL Server 的服务器以外的其他计算机上运行 Python 脚本,则需要在远程计算机上安装兼容的 SQL Server Native Client。

    SQL Native Client 可从 Esri 客户关怀中心门户网站下载。有关详细信息,请参阅设置到 SQL Server 的连接

  4. 在安装了 ArcGIS for Desktop标准版高级版)、ArcGIS Server Enterprise(Standard 或 Advanced)或具有 Geodatabase Update 扩展模块的 ArcGIS Engine 的计算机上,将这些示例脚本之一复制到 ArcGIS for Desktop 中的 Python 窗口或复制到任何 Python IDE(如 PythonWin 或 WING)中。

    此示例将创建数据库、sde 登录和方案(如果使用 sde 方案)、授予 sde 用户创建地理数据库的权限、创建数据库,然后创建地理数据库。

    """
    Name: create_enterprise_gdb.py
    Description: Provide connection information to a DBMS instance and create an enterprise geodatabase.
    Type  create_enterprise_gdb.py -h or create_enterprise_gdb.py --help for usage
    Author: Esri
    """
    
    # Import system modules
    import arcpy, os, optparse, sys
    
    
    # Define usage and version
    parser = optparse.OptionParser(usage = "usage: %prog [Options]", version="%prog 1.0 for 10.1 release")
    
    #Define help and options
    parser.add_option ("--DBMS", dest="Database_type", type="choice", choices=['SQLSERVER', 'ORACLE', 'POSTGRESQL', ''], default="", help="Type of enterprise DBMS:  SQLSERVER, ORACLE, or POSTGRESQL.")                   
    parser.add_option ("-i", dest="Instance", type="string", default="", help="DBMS instance name")
    parser.add_option ("-D", dest="Database", type="string", default="none", help="Database name:  Not required for Oracle")
    parser.add_option ("--auth", dest="Account_authentication", type ="choice", choices=['DATABASE_AUTH', 'OPERATING_SYSTEM_AUTH'], default='DATABASE_AUTH', help="Authentication type options (case-sensitive):  DATABASE_AUTH, OPERATING_SYSTEM_AUTH.  Default=DATABASE_AUTH")
    parser.add_option ("-U", dest="Dbms_admin", type="string", default="", help="DBMS administrator user")
    parser.add_option ("-P", dest="Dbms_admin_pwd", type="string", default="", help="DBMS administrator password")
    parser.add_option ("--schema", dest="Schema_type", type="choice", choices=['SDE_SCHEMA', 'DBO_SCHEMA'], default="SDE_SCHEMA", help="Schema Type for SQL Server geodatabase, SDE or DBO. Default=SDE_SCHEMA")
    parser.add_option ("-u", dest="Gdb_admin", type="string", default="", help="Geodatabase administrator user name")
    parser.add_option ("-p", dest="Gdb_admin_pwd", type="string", default="", help="Geodatabase administrator password")
    parser.add_option ("-t", dest="Tablespace", type="string", default="", help="Tablespace name")
    parser.add_option ("-l", dest="Authorization_file", type="string", default="", help="Full path and name of authorization file")
    # Check if value entered for option
    try:
    	(options, args) = parser.parse_args()
    
    	
    	#Check if no system arguments (options) entered
    	if len(sys.argv) == 1:
    		print "%s: error: %s\n" % (sys.argv[0], "No command options given")
    		parser.print_help()
    		sys.exit(3)
    
    	#Usage parameters for spatial database connection
    	database_type = options.Database_type.upper()
    	instance = options.Instance
    	database = options.Database.lower()	
    	account_authentication = options.Account_authentication.upper()
    	dbms_admin = options.Dbms_admin
    	dbms_admin_pwd = options.Dbms_admin_pwd
    	schema_type = options.Schema_type.upper()
    	gdb_admin = options.Gdb_admin
    	gdb_admin_pwd = options.Gdb_admin_pwd	
    	tablespace = options.Tablespace
    	license = options.Authorization_file
    	
    	
    	if (database_type == "SQLSERVER"):
    		database_type = "SQL_SERVER"
    	
    	if( database_type ==""):	
    		print " \n%s: error: \n%s\n" % (sys.argv[0], "DBMS type (--DBMS) must be specified.")
    		parser.print_help()
    		sys.exit(3)		
    		
    	if (license == ""):
    		print " \n%s: error: \n%s\n" % (sys.argv[0], "Authorization file (-l) must be specified.")
    		parser.print_help()
    		sys.exit(3)			
    	
    	if(database_type == "SQL_SERVER"):
    		if(schema_type == "SDE_SCHEMA" and gdb_admin.lower() != "sde"):
    			print "\n%s: error: %s\n" % (sys.argv[0], "To create SDE schema on SQL Server, geodatabase administrator must be SDE.")
    			sys.exit(3)
    		if (schema_type == "DBO_SCHEMA" and gdb_admin != ""):
    			print "\nWarning: %s\n" % ("Ignoring geodatabase administrator specified when creating DBO schema...")
    		if( account_authentication == "DATABASE_AUTH" and dbms_admin == ""):
    			print "\n%s: error: %s\n" % (sys.argv[0], "DBMS administrator must be specified with database authentication")
    			sys.exit(3)
    		if( account_authentication == "OPERATING_SYSTEM_AUTH" and dbms_admin != ""):
    			print "\nWarning: %s\n" % ("Ignoring DBMS administrator specified when using operating system authentication...")	
    	else:
    		if (schema_type == "DBO_SCHEMA"):
    			print "\nWarning: %s %s, %s\n" % ("Only SDE schema is supported on", database_type, "switching to SDE schema..." )
    			
    		if( gdb_admin.lower() == ""):
    			print "\n%s: error: %s\n" % (sys.argv[0], "Geodatabase administrator must be specified.")
    			sys.exit(3)
    
    		if( gdb_admin.lower() != "sde"):
    			if (database_type == "ORACLE"):
    				print "\nGeodatabase admin user is not SDE, creating user schema geodatabase on Oracle...\n"
    				sys.exit(3)
    			else:
    				print "\n%s: error: %s for %s.\n" % (sys.argv[0], "Geodatabase administrator must be SDE", database_type)
    				sys.exit(3)
    			
    		if( dbms_admin == ""):
    			print "\n%s: error: %s\n" % (sys.argv[0], "DBMS administrator must be specified!")
    			sys.exit(3)
    
    		if (account_authentication == "OPERATING_SYSTEM_AUTH"):
    			print "Warning: %s %s, %s\n" % ("Only database authentication is supported on", database_type, "switching to database authentication..." )
    
    	# Get the current product license
    	product_license=arcpy.ProductInfo()
    	
    	
    	# Checks required license level
    	if product_license.upper() == "ARCVIEW" or product_license.upper() == 'ENGINE':
    		print "\n" + product_license + " license found!" + " Creating an enterprise geodatabase requires an ArcGIS for Desktop Standard or Advanced, ArcGIS Engine with the Geodatabase Update extension, or ArcGIS for Server license."
    		sys.exit("Re-authorize ArcGIS before creating enterprise geodatabase.")
    	else:
    		print "\n" + product_license + " license available!  Continuing to create..."
    		arcpy.AddMessage("+++++++++")
    	
    	
    	try:
    		print "Creating enterprise geodatabase...\n"
    		arcpy.CreateEnterpriseGeodatabase_management(database_platform=database_type,instance_name=instance, database_name=database, account_authentication=account_authentication, database_admin=dbms_admin, database_admin_password=dbms_admin_pwd, sde_schema=schema_type, gdb_admin_name=gdb_admin, gdb_admin_password=gdb_admin_pwd, tablespace_name=tablespace, authorization_file=license)
    		for i in range(arcpy.GetMessageCount()):
    			arcpy.AddReturnMessage(i)
    		arcpy.AddMessage("+++++++++\n")
    	except:
    		for i in range(arcpy.GetMessageCount()):
    			arcpy.AddReturnMessage(i)
    			
    #Check if no value entered for option	
    except SystemExit as e:
    	if e.code == 2:
    		parser.usage = ""
    		print "\n"
    		parser.print_help()   
    		parser.exit(2)
    

    如果更希望预配置 SQL Server 数据库(例如希望指定另一种文件大小或位置),则可将此示例脚本复制到现有预配置 SQL Server 数据库中以启用地理数据库功能。

    """
    Name: enable_enterprise_gdb.py
    Description: Provide connection information to an enterprise database
    and enable enterprise geodatabase.
    Type enable_enterprise_gdb.py -h or enable_enterprise_gdb.py --help for usage
    Author: Esri
    """
    
    # Import system modules
    import arcpy, os, optparse, sys
    
    
    # Define usage and version
    parser = optparse.OptionParser(usage = "usage: %prog [Options]", version="%prog 1.0 for 10.1 release")
    
    #Define help and options
    parser.add_option ("--DBMS", dest="Database_type", type="choice", choices=['SQLSERVER', 'ORACLE', 'POSTGRESQL', 'DB2','INFORMIX','DB2ZOS', ''], default="", help="Type of enterprise DBMS:  SQLSERVER, ORACLE, POSTGRESQL, DB2, INFORMIX, or DB2ZOS.")
    parser.add_option ("-i", dest="Instance", type="string", default="", help="DBMS instance name")
    parser.add_option ("--auth", dest="account_authentication", type ="choice", choices=['DATABASE_AUTH', 'OPERATING_SYSTEM_AUTH'], default='DATABASE_AUTH', help="Authentication type options (case-sensitive):  DATABASE_AUTH, OPERATING_SYSTEM_AUTH.  Default=DATABASE_AUTH")
    parser.add_option ("-u", dest="User", type="string", default="", help="Geodatabase administrator user name")
    parser.add_option ("-p", dest="Password", type="string", default="", help="Geodatabase  administrator password")
    parser.add_option ("-D", dest="Database", type="string", default="none", help="Database name:  Not required for Oracle")
    parser.add_option ("-l", dest="Authorization_file", type="string", default="", help="Full path and name of authorization file")
    
    
    # Check if value entered for option
    try:
    	(options, args) = parser.parse_args()
    
    	
    #Check if no system arguments (options) entered
    	if len(sys.argv) == 1:
    		print "%s: error: %s\n" % (sys.argv[0], "No command options given")
    		parser.print_help()
    		sys.exit(3)
    	
    
    	#Usage parameters for spatial database connection
    	database_type = options.Database_type.upper()
    	instance = options.Instance
    	account_authentication = options.account_authentication.upper()
    	username = options.User.lower() 
    	password = options.Password	
    	database = options.Database.lower()
    	license = options.Authorization_file
    
    
    	if( database_type ==""):	
    		print " \n%s: error: \n%s\n" % (sys.argv[0], "DBMS type (--DBMS) must be specified.")
    		parser.print_help()
    		sys.exit(3)		
    		
    	if (license == ""):
    		print " \n%s: error: \n%s\n" % (sys.argv[0], "Authorization file (-l) must be specified.")
    		parser.print_help()
    		sys.exit(3)
    
    	if (database_type == "SQLSERVER"):
    		database_type = "SQL_SERVER"
    		
    	# Get the current product license
    	product_license=arcpy.ProductInfo()
    	
    	if (license == ""):
    		print " \n%s: error: %s\n" % (sys.argv[0], "Authorization file (-l) must be specified.")
    		parser.print_help()
    		sys.exit(3)
    	
    	# Checks required license level
    	if product_license.upper() == "ARCVIEW" or product_license.upper() == 'ENGINE':
    		print "\n" + product_license + " license found!" + "  Enabling enterprise geodatabase functionality requires an ArcGIS for Desktop Standard or Advanced, ArcGIS Engine with the Geodatabase Update extension, or ArcGIS for Server license."
    		sys.exit("Re-authorize ArcGIS before enabling an enterprise geodatabase.")
    	else:
    		print "\n" + product_license + " license available!  Continuing to enable..."
    		arcpy.AddMessage("+++++++++")
    	
    	# Local variables
    	instance_temp = instance.replace("\\","_")
    	instance_temp = instance_temp.replace("/","_")
    	instance_temp = instance_temp.replace(":","_")
    	Conn_File_NameT = instance_temp + "_" + database + "_" + username    
    	
    	if os.environ.get("TEMP") == None:
    		temp = "c:\\temp"	
    	else:
    		temp = os.environ.get("TEMP")
    	
    	if os.environ.get("TMP") == None:
    		temp = "/usr/tmp"		
    	else:
    		temp = os.environ.get("TMP")  
    	
    
    	Connection_File_Name = Conn_File_NameT + ".sde"
    	Connection_File_Name_full_path = temp + os.sep + Conn_File_NameT + ".sde"
    	
    	# Check for the .sde file and delete it if present
    	arcpy.env.overwriteOutput=True
    	if os.path.exists(Connection_File_Name_full_path):
    		os.remove(Connection_File_Name_full_path)
    	
    	print "\nCreating Database Connection File...\n"	
    	# Process: Create Database Connection File...
    	# Usage:  out_file_location, out_file_name, DBMS_TYPE, instnace, database, account_authentication, username, password, save_username_password(must be true)
    	arcpy.CreateDatabaseConnection_management(out_folder_path=temp, out_name=Connection_File_Name, database_platform=database_type, instance=instance, database=database, account_authentication=account_authentication, username=username, password=password, save_user_pass="TRUE")
            for i in range(arcpy.GetMessageCount()):
    		if "000565" in arcpy.GetMessage(i):   #Check if database connection was successful
    			arcpy.AddReturnMessage(i)
    			arcpy.AddMessage("\n+++++++++")
    			arcpy.AddMessage("Exiting!!")
    			arcpy.AddMessage("+++++++++\n")
    			sys.exit(3)            
    		else:
    			arcpy.AddReturnMessage(i)
    			arcpy.AddMessage("+++++++++\n")
    	
    	
    	# Process: Enable geodatabase...
    	try:
    		print "Enabling Enterprise Geodatabase...\n"
    		arcpy.EnableEnterpriseGeodatabase_management(input_workspace=Connection_File_Name_full_path, authorization_file=license)
    		for i in range(arcpy.GetMessageCount()):
    			arcpy.AddReturnMessage(i)
    		arcpy.AddMessage("+++++++++\n")
    	except:
    		for i in range(arcpy.GetMessageCount()):
    			arcpy.AddReturnMessage(i)
    			
    	if os.path.exists(Connection_File_Name_full_path):
    		os.remove(Connection_File_Name_full_path)
    			
    #Check if no value entered for option	
    except SystemExit as e:
    	if e.code == 2:
    		parser.usage = ""
    		print "\n"
    		parser.print_help() 
    		parser.exit(2)
    
  5. 修改此脚本以包含特定于您的站点的信息。
  6. 运行您复制和更改的脚本。

用于创建地理数据库的日志文件 (GDBCreateGeodatabase<#>.log) 会写入运行此脚本的计算机上为 %TEMP% 变量所指定的目录。

相关主题

9/15/2013