Database API Reference Guide updated

0 Flares 0 Flares ×

Check out the updated Titanium Mobile API Reference Guide for Database — there are some new code samples to help get you going.

One of the new examples shows how to store and retrieve a blob using the SQLite database. The blob datatype is pretty useful — in this example, it’s a very general datatype that stores an image. Suppose you have a JPEG image called ‘myphoto.jpg’ in your Resources directory. Let’s look at how you would read the image from the file, and then add it to the database.

var imageFile = Titanium.Filesystem.getFile(‘myphoto.jpg’);

var oneImage =;

The above code will read the image from your JPEG file, and store it into the oneImage variable.

Now let’s see how you could store images into a database. First, we’ll open a database file and create the database table using an SQL command.

var db ='images');

db.execute("CREATE TABLE IF NOT EXISTS pics (id INTEGER, image BLOB)");

Now that we have the database table, let’s insert our photo:

db.execute(“INSERT INTO pics (id,image) VALUES(?,?)”, 1, oneImage);

This inserts a row into the database table, with id equal to 1, and image containing the image as a blob. When it comes time to retrieve the image from the database, you’ll use code something like this:

var myResultSet = db.execute(“SELECT * FROM pics”);

if (myResultSet.isValidRow()) {

retrievedImage = myResultSet.field(1);



This will select all the rows from the database table, and set your retrievedImage variable to the image blob in the first row. At this point, you can do whatever you’d like with the image — you could display it in an ImageView, for example.

However, there’s a potential problem with the technique shown above. Depending on the size of your database table, the SQL command we used to select every row could return a result set that has many rows, and many images. This could take an unacceptably large amount of memory. So an improved technique would be to figure out first which image you need, and then select only the corresponding row(s). Here’s a modified SQL statement that selects only the first row in the database table:

var myResultSet = db.execute(“SELECT * FROM pics WHERE id=1”);

If you need to store pictures in your application, you should consider whether the database is the right solution. For most picture-taking applications, a better approach would be to store the pictures as files in memory, or on the memory card, and then use the database to store the names of those files.

You can see the complete sample app in the Titanium Mobile API Reference Guide for Database. Happy coding!

0 Flares Twitter 0 Facebook 0 LinkedIn 0 Email -- 0 Flares ×

Sign up for our blog!

computer and tablet showing Appcelerator software
Start free, grow from there.
0 Flares Twitter 0 Facebook 0 LinkedIn 0 Email -- 0 Flares ×