Sunday, August 5, 2012

SQLite wrapper based on java.lang.reflect

In Android development, data persistence is often realized with SQLite. Sometimes the act of preparing all the classes, the adapter, every kind of query (CRUD) and rewrap into model,is a bit frustrating. It's like something already done, to do again every time.

I never see this kind of class on the web, so I decided to make my own one.
What I'm talking about?

A class that simplifies the common use of SQLite with a friendly usage (inspired by .NET's LINQ one).
SQL Scripts are defined by the model, so you need to supply the object instance or just its class.

For the moment I provided:
  • select (distinct, count,where, limit, order by)
  • delete (where)
  • insert
  • transactions

Where statements miss of IN, NOT IN , BETWEEN clause... but I think to do them soon.
No track of JOIN, GROUPBY, CONSTRAINTS for now :(

Here the usage:

RSQLiteDatabase db=RSQLiteDatabase.getSingleton();

//create a DummyObject
DummyObject obj= new DummyObject();

MyObject myObj= new MyObject(1);

db.insert(obj) //obj.extra (if exists) will be serialized
List<DummyObject> list=
//select with where and limit of 10
  .where("field1",RSQLiteOperator.EQUALS, 100)
  .or("field1", RSQLiteOperator.LESSER_OR_EQUALS_THAN_, "300")
//select count
int count
    .where("field1",RSQLiteOperator.GREATER_THAN , 100)
    .and("field2", RSQLiteOperator.LIKE, "ita")
    .or("field3",SQLiteOperator.EQUALS, myObj)
//delete (can be combined with where)
int del= db.deleteFrom(DummyObject.class);

Insert insert= db.insert(new DummyObject());
RSQLiteDatabase.RSQLiteTransaction trans=db.beginTransaction();
for (int i = 0; i <8000; i++) 
List<Object> transa=trans.executeAll(this);

It's can honestly say it's all quite fast ,except SELECT of huge amount of data.
It's a single thread worker, but I'm planning to fork it according to bigness.

It's a open project you can find on

No comments:

Post a Comment