Dataset
Dataset instance is a result of SQLite database execution method. Instance is created automatically and if returned false, an error occurs. Dataset object contains all information selected from the databse. It contains names of columns and data in all rows. It provides information sequentially row by row. You move to the next row by using function next.
Name method is used to get name of the field, table or database. See table and example below how to use this feature. The name of the field is returned as default. Second parameter has following symbols:
#field |
returns name of the current field |
#table |
returns name of the table |
#database |
returns name of the database |
In this example, we use database with table users and three columns:
//create SQL query var result = database.exec("select * from users"); //name of second column, “firstName”
console<
console<
If we want to work in application that requires loaded data, dataset is not suitable for our requirements. Let’s create a function which gives us a JSON object as result. Expected format of object is { field : value, … }
Example data-set to JSON:
// Returns object constructed from current row as { field1: value1, field2: value2, etc. } Dataset.rowAsObject = function ()
{
var names = this.names;
if (!names)
{
names = [];
for (var n = 0; n < this.length; ++n)
names.push(symbol(this.name(n)));
this.names = names;
}
var obj = {};
var n = 0;
for (var v in this)
{
obj[names[n++]] = v;
}
return obj;
}
This function make json from one row. To go through the whole table, while cycle is usually used.
while (result) {
// create row object
row = result.rowAsObject();
// show values from the line in a list
app.list.add(new ListItem({text : "name: " + row.name + " surname: " + row.surname + "; age: " + row.age}));
// move to next line. If it does not exists break thy cycle
if (!result.next())
break;
}