databaseToCSV.sml

  Download

More scripts: Vector

Syntax Highlighing:

comments, key words, predefined symbols, class members & methods, functions & classes
            
# Cindy Robbins, 10Nov2004, updated 18March2010
#  samlple script to show how navigate through all of the tables, fields & records in a vector's polgyon database.
#  It prints the number of polygons in vector, and the number of fields and records of each table.
#  A .csv file is created for every table
#  Use a vector with polygons as input (try it with the cbsoils_lite vector found in the cb_data/cb_soils.rvc file,
#  which is located with the sample data that comes with TNTmips.)
class RVC_VECTOR V;
class DATABASE database, db;
class DBTABLEINFO tableInfo;
class DBFIELDINFO fieldInfo;
numeric polyCount, tableCount, fieldCount, count1, count2, count3, i, numRecs;
string heading$, record$, fileName$, tableName$;
class FILE myfile; # for .csv files
clear();  # clear console window
GetInputVector(V);
polyCount = V.$Info.NumPolys;
db = OpenVectorPolyDatabase(V);  # using polygon database
print(DateToString(Date(), "%d%B%Y"));
print("There are ", polyCount, " polygons and the following ", db.NumTables, " tables ", "in the ", V.$Info.Filename, " ", V.$Info.Name," vector object.");
# Go through all of the tables in the database
tableCount = db.NumTables ;
for count1 = 1 to tableCount {
   tableInfo = DatabaseGetTableInfo(db,count1);
   print();
   print("   The ", tableInfo.Name, " table has",  tableInfo.NumFields, " field(s) and", tableInfo.NumRecords, " record(s):");
 
   # Go through all of the fields in the table and print header
   fieldCount = tableInfo.NumFields;
   heading$ = "";
   for count2 = 1 to fieldCount {
      fieldInfo = FieldGetInfoByNumber(tableInfo, count2);
      heading$ = heading$ + fieldInfo.Name + ", ";
   }
   tableName$ = tableInfo.Name;
   fileName$ = "c:\" + tableName$ + ".csv";
   myfile =  fopen(fileName$);
   fprint (myfile, heading$);  # prints a .csv file for every table in polygon database
   # print out records
   numRecs = tableInfo.NumRecords;
   for i = 1 to numRecs{   
      record$ = "";
      for count3 = 1 to fieldCount { 
         record$ = record$  + TableReadFieldStr(tableInfo, count3, i) + ", ";
      }
      fprint(myfile, record$);   # prints records to .csv file
 #     print(record$);  # prints each record to console
   }
fclose(myfile);
}
print("Done.");