Wednesday, January 12, 2011

A Terse SQLite API for Adobe AIR

Love the native SQLite support in Adobe AIR. Hate how verbose it is.

Here's my attempt at an API which supports pithier code:

Grab the Db object here. Below are some examples that show usage.

Use & Enjoy!

// Setup
db:Db = new Db();
db.sqlConnection = ... // magic construct your sql connection

// Run a statement and ignore the results
db.exec("CREATE TABLE IF NOT EXISTS people(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, ph TEXT)");

// Same as above, but use parameters
for(var i:int = 0; i < 10; i++) {
  db.exec(["INSERT INTO people(name,ph) VALUES(?,?)", "Foo" + i, "555-" + (1212 + i)]);
}

// Extract data from DB and put it into an imaginary UI
db.each("SELECT * FROM people WHERE name LIKE 'A%'",
        function(row:Object):void {
          ui.updateUi(row.name, row.ph);
        });

// Same as above, but work with a single row
db.first(["SELECT COUNT(*) AS num FROM people WHERE name LIKE ?", query],
         function(found) {
          if(found) {
            ui.setStatus("There are " + found.num + " matches");
          } else {
            ui.setStatus("Oh uh, nothing found!");
          }
         });

No comments:

Post a Comment