Daily Snippet, Developer to developer

python’s time:how to add column in ArcSDE Tables and fill the value

## Script untuk menambah kolom OLD_FID, OLD_TDATAID, dan UNIT, kemudian mengisinya.
## Inputan : Feature Dataset dan Unit.
## Dilakukan per unit.
import sys, os, re, arcgisscripting, datetime, logging

gp = arcgisscripting.create()
inDataset = gp.GetParameterAsText(0)
unit = gp.GetParameterAsText(1)
logging_path = gp.GetParameterAsText(2)
##  set logging ke file
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=logging_path,
                    filemode='w')

def log_me(gp, msg, is_info):
    gp.AddMessage(str_log)
    if is_info == 1:
        logging.info(str_log)
    else:
        logging.error(str_log)

##boolean method special jika ada error di tengah jalan, maka feature yang dicatat di list_proceed_fc akan di-ignore.
def isInListProceed(nama_fc):

##   list_proceed_fc mencatat feature yang telah diproses, misal: 'SDE.MRuteBM', 'SDE.MTrafo', dan 'SDE.MBlokGardu'
##   list_proceed_fc=('SDE.MRuteBM', 'SDE.MTrafo', 'SDE.MBlokGardu')
    
   list_proceed_fc=('')
   for fcPro in list_proceed_fc:
       if fcPro == nama_fc:
           return True
   return False 

try:
    from time import gmtime, strftime
    str_log = ""

    str_log = "Unit : %s " % unit
    log_me(gp,str_log,1)
    gp.workspace = inDataset

    # Get a list of feature classes in the workspace.
    fcs = gp.ListFeatureClasses()
        
    # Loop through the list of feature classes.
    fcs.reset()
    fc = fcs.next()
    
##    Deklarasi list feature class yang akan diproses
    listProceedFc = []

    while fc:
        listProceedFc.append(str(fc))
        
##      log feature yang akan diproses        
        str_log = "list featureclass : %s " % listProceedFc
        logging.info(str_log)
	
        str_log = "Nama featureclass : %s " % fc
        log_me(gp, str_log, 1)

        
##        Syarat add field  dan pengisian data adalah tidak ada user lain yang locking
##        Add field OLD_FID, Double(38,8)
        try:    
            gp.AddField_management(fc, "OLD_FID", "DOUBLE", 38, 8)
        except Exception, ErrorFieldExists:
            str_log = "Kolom OLD_FID telah ditambahkan."
            log_me(gp, str_log, 1)
            
##        Add field OLD_TDATAID, Double(38,8)
        try:
            gp.AddField_management(fc, "OLD_TDATAID", "DOUBLE", 38, 8)
        except Exception, ErrorFieldExists:
            str_log = "Kolom OLD_TDATAID telah ditambahkan."
            log_me(gp, str_log, 1)

##        Add field UNIT, Text(50)
        try:
            gp.AddField_management(fc, "UNIT", "TEXT", 50)
        except Exception, ErrorFieldExists:
            str_log = "Kolom UNIT telah ditambahkan."
            log_me(gp, str_log, 1)

##        Add field OLD_GLOBALID, Text(50)
        try:    
            gp.AddField_management(fc, "OLD_GLOBALID", "TEXT", 50)
        except Exception, ErrorFieldExists:
            str_log = "Kolom OLD_GLOBALID telah ditambahkan."
            log_me(gp, str_log, 1)

##      update row cursor OLD_FID sangat lambreta. coba ganti dengan gp.CalculateField_management
        gp.AddMessage("CalculateField OLD_FID from OBJECTID on %s " % strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
        gp.CalculateField_management(fc,"OLD_FID", "!OBJECTID!", "PYTHON")

##      update field OLD_GLOBALID menggunakan value dari GLOBALID
        gp.AddMessage("CalculateField OLD_GLOBALID from GLOBALID on %s " % strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
        gp.CalculateField_management(fc,"OLD_GLOBALID", "!GLOBALID!", "PYTHON")
        
##        update old_tdataid terpaksa menggunakan cursor karena calculatefield tidak stabil
        str_log = "Sedang memproses OLD_TDATAID dari TDATA_ID yang <> None dan <> 0 ..."
        log_me(gp, str_log, 1)
        try:
    ##      Get data feature class         
            rows = gp.UpdateCursor(fc, "TDATA_ID IS NOT NULL AND TDATA_ID > 0", "", "TDATA_ID; OLD_TDATAID")
            row = rows.Next()

            i=1
            while row <> None:
##                tulis ke log jika sudah mencapai 5000 record
                if i % 5000 == 0:
                    str_log = "Record %s ke %s." % (fc,i)
                    logging.info(str_log)
                                        
                objTDATAID_old = row.GetValue("TDATA_ID")
                row.SetValue("OLD_TDATAID", objTDATAID_old)
                rows.UpdateRow(row)
                i += 1
                row = rows.Next()
       
            # Delete row yang digunakan sebagai koleksi data feature class
            del row, rows
        except Exception, ErrorTDataID:
            del row, rows
            str_log = "Error set value TDataID %s" % str(ErrorTDataID)
            logging.error(str_log)
        

        str_log = "CalculateField UNIT from x on %s " % strftime("%a, %d %b %Y %H:%M:%S", gmtime())
        log_me(gp, str_log, 1)
        gp.CalculateField_management(fc,"UNIT", "x", "PYTHON", "x = '" + unit + "'")

        fc = fcs.next()
except Exception, ErrorDesc:
    str_log = "error desc %s" % str(ErrorDesc)
    log_me(gp, str_log, 0)
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s