Monday, August 19, 2013

Creating an SQLite Driven app for Windows 8 with PhoneGap/ Cordova

A few of us out there might have seen how easy getting an app done is with Cordova for Windows 8.

It's setup is probably the easiest of the lot.

However, while this is true, it lacks the documentation level the other platforms have.

Here is a simple way to have SQLite available in your PhoneGap Windows 8 Project.

1. Open your VS(Visual Studio).
2. Tools > Extensions and Updates.
3. Online >Search for SQLite in the search field and Download SQLite for Windows Runtime.
   Visual Studio Extensions dialog
4. Create a Cordova Windows 8 project (Use Cordova 2.9 as there are isues currently with 3.0).
5. Right click project solution and select add reference.
6. Check Add C++ Runtime and SQLite Runtime
Add Reference dialog
7. Download a WinRT Wrapper Library(Yes PhoneGap still works so don't worry)
8. Extract the content of the file downloaded above.
9. Add the  SQLite3Component\SQLite3Component.vcxproj  from project the project your project (File > Add Existing Project > Select above file from the folder you extracted in 8 above)
8. Right Click project solution once again and and select reference
10. Check Add SQLite3Component\SQLite3Component.vcxproj 
11. Right Click WWW/JS folder and add existing file(Select SQLite3JS\js\SQLite3.js from directory in 8).
12. Drag the reference to the JS into your project and get building.

You can test if configuration works with the following code:

var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\db.sqlite';
SQLite3JS.openAsync(dbPath)
.then(function (db) {
  return db.runAsync('CREATE TABLE Item (name TEXT, price REAL, id INT PRIMARY KEY)')
  .then(function () {
    return db.runAsync('INSERT INTO Item (name, price, id) VALUES (?, ?, ?)', ['Mango', 4.6, 123]);
  })
  .then(function () {
    return db.eachAsync('SELECT * FROM Item', function (row) {
      alert('Get a ' + row.name + ' for $' + row.price);
    });
  })
  .then(function () {
    db.close();
  });
});

*I  used alert in place of the original console.log so you can confirm it works within the project.

You can add plugins you create with no problems.

Special Thanks to Tim Huer for instructions on setting up SQLite for Windows 8 and Marcus Ilgner for creating the the SQLite-WinRT Wrapper for Windows 8.

Ismael O. Jimoh

1 comment:

  1. Thanks for your instructions. Is it possible that the SQLite Runtime can't be found in VS 2013 Express (German)?

    ReplyDelete