I would like to load person data from a CSV file and store it on my database.
The Person Data Class looks as follows:
DataClass Person Begin
Property[firstName, String, None, 'the firstname of the person'];
Property[lastName, String, None, 'the lastname of the person'];
End
The property names of the Person Class are important. We use them in the CSV file as column headers:
firstName;lastName
Stan;Marsh
Kyle;Brosflovski
Eric;Cartmen
Kenny;McCormick
Butters;Stotch
Clyde;Donovan
The import script is straightforward. We use a "Try-Catch-Finally" structure to handle exceptions.
The csv file can be read using the LOADFROMCSV function. The transaction is handled using SqlOpen / SqlCommit / SqlRollback / SqlClose functions.
IMPORTANT! The functions that are modifying data on the database (i.e. SqlQuery, SaveDataEntity) must use NULL as the data source name.
If you have to perform an SqlQuery and you want to manage the transactionality with SqlOpen and autocommit false, put the DataSourceName to null as a first parameter of the SqlQuery, otherwise a new SqlContext will be created, and the autocommit option will be set to true.
Here's a brief explanation of the script below:
- First, the database connection for the transaction is opened using
SqlOpen command. - In the Try section, we then load the data using
LOADFROMCSV and store it in the database using SaveDataEntity. - If everything goes well, we commit everything using
SqlCommit. - The Catch section is entered if an exception occurs. Here, we handle the error and revert previous database commands using
SqlRollback. It is good practice to output log information in case an exception occurs. - The Finally section is always executed: we close the database connection using
SqlClose.
// define variables
Person $person;
Indexed Person $persons;
// open a database connection / autocommit disabled
SqlOpen('H2', false);
Try
// load data from csv file
$persons := LOADFROMCSV(Person, 'work/persons.csv', ';');
// iterate loaded data and save to database
ForEach $person In $persons Do
SaveDataEntity($person, null, true);
End
// everything was successfull, commit
SqlCommit();
Catch
// there was an exception, roll back
SqlRollback();
// output some log information
LOGGER('error', JOIN('exception occurred:', StackTrace($exception)));
Finally
// always close the database connection
SqlClose();
End