Monday, May 2, 2011

Working with SQLite in AIR: Part 9

Today we'll learn about handling the results of a SELECT command.

Most of the time, you need to handle the results for all the commands you execute. You need to listen and react somehow to an error event, for example, you could alert the user that a error has occured, or retry the operation.

If we are using the SELECT command, we always need to do the handling, because we need to actually extract the results. We can do that using the getResult() of the SQLStatement object. This method returns a SQLResult object, that has a property called data, which is an associative array. This array contains all the data that we've got using the SELECT command. Each element is an Object and each of them has properties with the same names as the returned table columns from the database.

Anyway, now let's write some code. In the previous tutorial we've learned how to set the listeners for both results and error events, now let's see an example of what we could have in a results handling function.

What we do is create a reference to the SQLStatement object, then create an SQLResult object and apply the results of the SQL command to it using the getResult() method of the SQLStatement object. Afterwards, we need to check if the results contain anything. If they do, create a new array and store the information in it.

function onResult(evt:SQLEvent):void{
var st:SQLStatement = evt.target as SQLStatement;
var res:SQLResult = st.getResult();
if (res != null && res.data != null){
var myData:Array = res.data;
}
}

The array will now contain Objects, where each element has a property for each of the columns in the table (as I said before). But it is also possible to create your own object type for the results. For example, we could have a pre-defined AS3 class called Contact, that has properties called id, fname, lname, age, etc. It is possible to actually turn the resulted data into Contact object.

We can do that by applying a reference to your custom class to the itemClass property of the SQLStatement object. We need to do that before we call the execute() method, though.

myStat.itemClass = Contact;

That's all for today, folks.

Thanks for reading!

Related:

Working with SQLite in AIR: Part 1
Working with SQLite in AIR: Part 2
Working with SQLite in AIR: Part 3
Working with SQLite in AIR: Part 4
Working with SQLite in AIR: Part 5
Working with SQLite in AIR: Part 6
Working with SQLite in AIR: Part 7
Working with SQLite in AIR: Part 8
Working with SQLite in AIR: Part 10
Working with SQLite in AIR: Part 11
Working with SQLite in AIR: Part 12

No comments:

Post a Comment