Skip to main content

在 Python 中验证表和字段名称

验证表名

地理数据库使用各种关系数据库管理系统 (RDBMS) 来维护组成地理数据库的许多表。 地理数据库中的所有表都必须具有有效名称,因此在地理数据库中创建数据时,必须要有一种机制检查表名是否有效。 使用 ValidateTableName() 函数时,可通过脚本确定特定名称对于特定工作空间而言是否有效。

以下是将要验证的表名错误:

  • 表与数据源的保留字同名(例如,Table)。

  • 表包含无效字符。

  • 表的起始字符无效(例如,使用数字作为第一个字符)。

注:

ValidateTableName 函数不用于确定指定名称对于指定工作空间而言是否唯一。 Exists 函数可以检查表名对于给定工作空间而言是否唯一。

函数

说明

ValidateTableName (name, {workspace})

会获取表名和工作空间路径,并返回工作空间的有效表名。

ValidateTableName 函数

通过将工作空间指定为参数,ArcPy 可以检查所有现有表名,并确定输出工作空间是否存在命名限制。 如果输出工作空间是 RDBMS,则它可能具有不能在表名中使用的保留字。 还可能包含不能在表或字段名称中使用的无效字符。 所有无效字符都将替换为下划线 (_)。 ValidateTableName 可返回表示有效表名的字符串,如果输入名称有效,则该字符串可能与输入名称相同。 下面的示例可保证由复制要素工具创建的新输出要素类具有在任何地理数据库中都有效的唯一名称:

"""Move all shapefiles from a folder into a geodatabase"""
import arcpy
# Set the workspace. List all of the shapefiles
arcpy.env.workspace = "d:/St_Johns"
fcs = arcpy.ListFeatureClasses("*")
# Set the workspace to SDE for ValidateTableName
arcpy.env.workspace = "Database Connections/Bluestar.sde"
# For each feature class name
for fc in fcs:
 # Validate the output name so it is valid
 outfc = arcpy.ValidateTableName(fc)
 # Copy the features from the workspace to a geodatabase
 arcpy.management.CopyFeatures(fc, outfc)

验证字段名称

每个数据库都可以对表中的字段名称有命名限制。 要素类或关系类等对象作为表存储在 RDBMS 中,因此这些限制影响的不仅仅是独立表。 这些限制在各种数据库系统中可能常见,也可能不常见,因此脚本应检查所有新字段名称,以确保工具在执行过程中不会失败。

以下是将要验证的字段名称错误:

  • 字段与数据源的保留字同名(例如,Table)。

  • 字段与之前定义的字段同名。

  • 字段包含无效字符(例如,*)。

  • 字段名称超出数据源的最大字段名称长度。

函数

说明

ValidateFieldName (name, {workspace})

使用字符串(字段名称)和工作空间路径,并根据输出地理数据库中的名称限制返回有效的字段名称。

ValidateFieldName 函数

下面的示例可确保使用 ValidateFieldName 函数添加字段,而不考虑输入名称:

"""
Create a new numeric field containing the ratio of polygon area to
polygon perimeter. Two arguments, a feature class and field name,
are expected.
"""
# Define a pair of simple exceptions for error handling
class ShapeError(Exception):
 pass
class FieldError(Exception):
 pass
import arcpy
import os
try:
 # Get the input feature class and make sure it contains polygons
 input = arcpy.GetParameterAsText(0)
 desc = arcpy.Describe(input)
 if desc.shapeType.lower() != "polygon":
     raise ShapeError
 # Get the new field name and validate it
 fieldname = arcpy.GetParameterAsText(1)
 fieldname = arcpy.ValidateFieldName(fieldname, os.path.dirname(input))
 # Make sure shape_length and shape_area fields exist
 if len(arcpy.ListFields(input, "Shape_area")) > 0 and \
     len(arcpy.ListFields(input, "Shape_length")) > 0:
     # Add the new field and calculate the value
     arcpy.management.AddField(input, fieldname, "double")
     arcpy.management.CalculateField(input, fieldname,
                                     "[Shape_area] / [Shape_length]")
 else:
     raise FieldError
except ShapeError:
 print("Input does not contain polygons")
except FieldError:
 print("Input does not contain shape area and length fields")
except arcpy.ExecuteError:
 print(arcpy.GetMessages(2))