Retrieving Data

In order to test the retrieval abilities of both databases we will try to select a car with a pilot having 9 points:

SQLite:

SqlExample.java: selectCar
01public static void selectCar() { 02 SQLiteDatabase db = database(); 03 if (db != null){ 04 long startTime = System.currentTimeMillis(); 05 Cursor c = 06 db.query("select c.model, p.name, p.points from car c, pilot p where c.pilot = p.id and p.points = 9;", null); 07 if (c.count() == 0) { 08 logToConsole(0, "Car not found, refill the database to continue.", false); 09 return; 10 } 11 c.first(); 12 Pilot pilot = new Pilot(); 13 pilot.setName(c.getString(1)); 14 pilot.setPoints(c.getInt(2)); 15 16 Car car = new Car(); 17 car.setModel(c.getString(0)); 18 car.setPilot(pilot); 19 logToConsole(startTime, "Selected Car (" + car + "): ", false); 20 } 21 }

db4o:

(Using SODA query)

Db4oExample.java: selectCar
01public static void selectCar() { 02 ObjectContainer container = database(); 03 if (container != null){ 04 Query query = container.query(); 05 query.constrain(Car.class); 06 query.descend("pilot").descend("points").constrain(new Integer(9)); 07 08 long startTime = System.currentTimeMillis(); 09 ObjectSet result = query.execute(); 10 if (result.size() == 0){ 11 logToConsole(0, "Car not found, refill the database to continue.", false); 12 } else { 13 logToConsole(startTime, "Selected Car (" + result.next() + "): ", false); 14 } 15 } 16 }

Of course SODA query is not the best db4o querying mechanism: the preferred mechanism  - Native Queries - will be reviewed in the following chapters. However, SODA is the closest to SQL and can server a good comparison. In the example above you can see that SQLite needs a lot of additional code to transfer the retrieved data into application's objects, whereas db4o does not need this code at all, as the result is already a collection of objects.