Thursday 15 November 2012

Java Blackberry database management

Blackberry java development allows to create a database on the device. There are many possible ways to create database. I have recently used Sqlite database for my application. Following is what I have done to use that with my application.

1) Create a database through through blackberry emulator. Following is the code to do that. 

 URI uri = URI.create("file:///SDCard/Databases/employee.db");
 Database sqliteDB = DatabaseFactory.create(uri);
 Statement st = sqliteDB.createStatement("CREATE TABLE Employee ("
 +"ID       INTEGER PRIMARY KEY,"
 +"name     TEXT,"
 +"number   TEXT,"
 );");
 st.prepare();
 st.execute();
 

2) A db file will be created in the file system. Open that db file. Insert as many data as you need. I have been required to insert data like this. As I had a large number of records that i needed in db on start up time only. I have tried to insert data through java program only. But i was facing issue about memory consumption. If you don't have too many data you can insert run time. 

3) Following is the code to retrieve data from database. 

 Statement st1 = sqliteDB.createStatement("select * from Employee;");
 st1.prepare();
 Cursor c = st1.getCursor();
 Row r;
 int count=0;
 while (c.next()) {
 r = c.getRow();
 String name = r.getString(1);
 }
 

If you have close database connection. You need to open the connection again before you go to retrieve data from the database. 

 sqliteDB = DatabaseFactory.open(uri);
 

This is just an example. Your implementation can be differ as per your requirement.