免费视频|新人指南|投诉删帖|广告合作|地信网APP下载

查看: 1079|回复: 4
收起左侧

[求助] 依据标准数据库创建要素,但总是出错,求助

[复制链接]

1

主题

886

铜板

0

好友

助理工程师

Rank: 5Rank: 5

积分
105
发表于 2021-8-2 16:04 | 显示全部楼层 |阅读模式
#coding=utf8


import arcpy
import os
import sys
import math
from arcpy.sa import *


# 初始化进度条
def initProgress(hint, num):
    arcpy.SetProgressor("step", u"正在" + hint, 0, num, 1)


# 进度条
def step():
    arcpy.SetProgressorLabel(u"正在进行....")
    arcpy.SetProgressorPosition()


# 释放进度条
def freeProgress():
    arcpy.ResetProgressor()


def get_Countt(inFeature):
    result = arcpy.GetCount_management(inFeature)
    count = int(result.getOutput(0))

    #count = int(result.getOutput(0))
    return count


# 获得唯一值
def getuniqueValue(inTable, inField):
    rows = arcpy.Searchcursor(inTable, inField)
    # Create an empty list
    uniqueList = []
    try:
        for row in rows:
            # If the value is not aLready in the list,append it
            if row[0] not in uniqueList:
                uniqueList.append(row[0])
        return uniqueList
    finally:
        if row:
            del row
        if rows:
            del rows


def getTable(tname):
    mypath = inWorkspace
    arcpy.env.workspace = mypath
    if isshp == True:
        if arcpy.Exists(mypath + os.sep + tname + ".dbf"):
            return mypath + os.sep + tname + ".dbf"
    else:
        if arcpy.Exists(mypath + os.sep + tname):
            return mypath + os.sep + tname
    return None


def getFeatureclass(featurename):
    mypath = inWorkspace
    arcpy.env.workspace = mypath
    if isshp == True:
        if arcpy.Exists(mypath + os.sep + featurename + ".shp"):
            return mypath + os.sep + featurename + ".shp"
    else:
        if arcpy.Exists(mypath + os.sep + featurename):
            return mypath + os.sep + featurename
    datasets = arcpy.ListDatasets("", "Feature")
    for dataset in datasets:
        curpath = mypath + os.sep + dataset
        if arcpy.Exists(curpath + os.sep + featurename):
            return curpath + os.sep + featurename
    return None


def updateFie1dalias(TableName, FieldName, alias):
    desc = arcpy.Describe(TableName)
    FieldName = FieldName.upper()
    for field in desc.fields:
        if field.Name.upper() == FieldName:
            if field.aliasName != alias:
                arcpy.AlterField_management(TableName, FieldName, new_field_alias=alias)  # 修改别名
                # #field.aliasName=alias
                arcpy.AddMessage(u"modify'table={2},{0}={1}'".format(FieldName, alias, TableName))
            break


def FieldExists(TableName, FieldName):
    desc = arcpy.Describe(TableName)
    for field in desc.fields:
        if field.Name.upper() == FieldName.upper():
            return True
            break
    return False


def Create_Table(ftable):
    num = get_Countt(ftable)
    initProgress("create", num)
    inField = ["表名", "表英文", "类型"]
    rows = arcpy.da.SearchCursor(ftable, inField)
    try:
        for row in rows:

            step()
            ptype = row[2]
            etable = row[1]
            ctable = row[0]
            arcpy.AddMessage("etable=" + etable + ",ctable=" + ctable)
            if ptype == 0:
                table = getTable(etable)
                if table == None:
                    arcpy.CreateTable_management(inWorkspace, etable)
                    if not isshp:  # 数据库有别名
                        arcpy.AlterAliasName(inWorkspace + os.sep + etable, ctable)  # 修改中文
            elif ptype < 4:
                inFeature = getFeatureclass(etable)
                geometry_type = "POINT"
                if ptype == 2:
                    geometry_type = "POLYLINE"
                elif ptype == 3:
                    geometry_type = "POLYGON"
                if inFeature == None:

                    arcpy.CreateFeatureclass_management(inWorkspace, etable, geometry_type, spatial_reference=sr)
                    # arcpy.createFeatureclass_management(inworkspace,etable, gepmetry_type)
                    # template=""#"",has_m="DISABLED" , has_z="DISABLED" , spatial_reference=sr)
                    if not isshp:  # 数据库有别名
                        arcpy.AlterAliasName(inWorkspace + os.sep + etable, ctable)  # 修改中文


    finally:
        freeProgress()
        if row:
            del row
        if rows:
            del rows


def get_FieldType(Fieldtype, Fieldlen):
    Fieldtype = Fieldtype.upper()
    if Fieldtype == "INT" and Fieldlen < 5:
        return "SmallInteger"
    elif Fieldtype == "INT":
        return "Integer"
    elif Fieldtype == "INTEGER":
        return "Integer"
    elif Fieldtype == "DOUBLE":
        return "Double"
    elif Fieldtype == "FLOAT":
        return "Double"
    elif Fieldtype == "STRING":
        return "String"
    elif Fieldtype == "CHAR":
        return "String"
    else:
        return "Date"


def add_one_Field(fieldtable, sql, layername, inFeature):
    rows = arcpy.da.SearchCursor(fieldtable, ["字段名", "字段英文", "字段类型", "长度", "小数位"], sql,sql_clause=(None, "order by ordid"))
    try:
        for row in rows:
            eField = row[0]
            cField = row[1]
            Fieldtype = row[2]
            Fieldlen = row[3]
            fieldPrecision = row[4]
            if not (FieldExists(inFeature, eField)):
                FType = get_FieldType(Fieldtype, Fieldlen)
                try:
                    if FType.upper() == "Double".upper():
                        arcpy.AddField_management()
                        arcpy.AddField_management(inFeature, cField, field_type="DOUBLE",
                        field_precision=Fieldlen, field_scale=fieldPrecision,
                        field_alias=eField)
                    else:
                        arcpy.AddField_management(inFeature, eField, FType, "#", "#", Fieldlen,
                            cField)
                #except Exception:
                except Exception:
                #except Exception,ErrorDesc:
                    arcpy.AddWarning(u"错误:" + str(ErrorDesc))
    finally:

        del rows,row


def add_Field(layertable, fieldtable):
    num = get_Countt(layertable)
    inField = ["表英文"]
    initProgress("add_Field", num)
    rows = arcpy.da.SearchCursor(layertable, inField)

    try:
        for row in rows:
            step()
            etable = row[0]
            inFeature = getFeatureclass(etable)
            if inFeature == None:
                continue
            sql = "图层名='" + etable + "'"
            add_one_Field(fieldtable, sql, etable, inFeature)

    finally:
        freeProgress()
        if row:
            del row
        if rows:
            del rows


def Main():
    scriptPath = sys.path[0]
    mdbpath = scriptPath + os.sep + "Convert.mdb"
    ftable = mdbpath + os.sep + "图层名"
    fieldtable = mdbpath + os.sep + "字段"
    Create_Table(ftable)
    add_Field(ftable, fieldtable)


inWorkspace = arcpy.GetParameterAsText(0)
SR = arcpy.GetParameter(1)  # 坐标系
# iscLockwise=arcpy.GetParameter(4)#是否顺时针,软件自动处理,顺时针

sr =arcpy.SpatialReference()

sr.loadFromString(SR)
XY = arcpy.GetParameter(2)

sr.XYTolerance = XY
arcpy.env.XYTolerance = str(XY) + " Meters"
outdesc = arcpy.Describe(inWorkspace)
isshp = True

if outdesc.dataType == "Workspace":
    isshp = False
    Main()
elif not outdesc.dataType == "Folder":  # 如FeatureDataset FeatureLayer
    arcpy.AddError(u"格式错误无法裁剪")
else:
    Main()


0

主题

689

铜板

1

好友

技术员

Rank: 3Rank: 3

积分
64
发表于 2021-8-13 14:55 | 显示全部楼层
错误代码贴上来啊
回复 支持 反对

使用道具 举报

1

主题

886

铜板

0

好友

助理工程师

Rank: 5Rank: 5

积分
105
 楼主| 发表于 2021-8-19 11:44 | 显示全部楼层
finally:
        freeProgress()
        if row:
            del row
        if rows:
            del rows


说是没有定义 row
回复 支持 反对

使用道具 举报

30

主题

2万

铜板

59

好友

钻石会员

Rank: 26Rank: 26Rank: 26Rank: 26Rank: 26Rank: 26Rank: 26

积分
6284
QQ
发表于 2022-2-12 15:59 | 显示全部楼层
感谢分享:mg
回复 支持 反对

使用道具 举报

37

主题

2万

铜板

111

好友

钻石会员

Rank: 26Rank: 26Rank: 26Rank: 26Rank: 26Rank: 26Rank: 26

积分
5763
发表于 2022-2-15 16:26 | 显示全部楼层
这是python代码,row没有定义
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

在线客服
快速回复 返回顶部 返回列表