Updating data

Modifying data is done by means of implementing your own update scripts that are then submitted to the DataContext's executeUpdate(...) method. This approach guarantees isolation and coherence in all update operations. Here is a simple example:

   1 File myFile = new File("unexisting_file.csv");
   2 
   3 UpdateableDataContext dataContext = DataContextFactory.createCsvDataContext(myFile);
   4 final Schema schema = dataContext.getDefaultSchema();
   5 dataContext.executeUpdate(new UpdateScript() {
   6 
   7     public void run(UpdateCallback callback) {
   8     
   9         // CREATING A TABLE
  10     
  11         Table table = callback.createTable(schema, "my_table")
  12             .withColumn("name").ofType(VARCHAR)
  13             .withColumn("gender").ofType(CHAR)
  14             .withColumn("age").ofType(INTEGER)
  15             .execute();
  16         
  17         // INSERTING SOME ROWS
  18         
  19         callback.insertInto(table).value("name","John Doe").value("gender",'M').value("age",42).execute();
  20         callback.insertInto(table).value("name","Jane Doe").value("gender",'F').value("age",42).execute();
  21     }
  22   
  23 });

If you just want to insert or update a single record, you can skip the UpdateScript implementation and use the pre-built InsertInto, Update or DeleteFrom classes. But beware though that then you don't have any transaction boundaries or isolation inbetween those calls:

   1 Table table = schema.getTableByName("my_table");
   2 dataContext.executeUpdate(new InsertInto(table).value("name", "Polly the Sheep").value("age", -1));
   3 dataContext.executeUpdate(new Update(table).where("name").eq("Polly the Sheep").value("age", 10));
   4 dataContext.executeUpdate(new DeleteFrom(table).where("name").eq("Polly the Sheep"));

... And just to go full circle, here's how you can continue to explore the data:

   1 System.out.println("Columns: " + Arrays.toString(table.getColumnNames()));
   2 
   3 DataSet ds = dc.query().from(table).select(table.getColumns()).orderBy(table.getColumnByName("name")).execute();
   4 while (ds.next()) {
   5     System.out.println("Row: " + Arrays.toString(ds.getRow().getValues()));
   6 }

This snippet will print out:

Columns: [name, gender, age]
Row: [Jane Doe,F,42]
Row: [John Doe,M,42]


CategoryExamples

examples/UpdatingData (last edited 2013-08-01 09:43:05 by KasperSorensen)