JS function to count rows in SQLite table - javascript

I'm trying to make a JS function that counts rows in an SQLite table.
function countRows(){
db.transaction(function (tx){
tx.executeSql('SELECT id FROM table', [], function (tx, results) {
var len = results.rows.length;
alert(len);
});
});
}
The above code displays an alert with numbers of rows in the table. However, I'd like to make a function that would return the number instead of showing the alert box.
I tried:
function countRows(){
db.transaction(function (tx){
tx.executeSql('SELECT id FROM table', [], function (tx, results) {
var len = results.rows.length;
return len;
});
});
}
And then:
var number = countRows();
alert (number); // returns "undefined"
The above example returns "undefined", whereas a parallel example works fine:
function count(){
return 3;
}
var number = count();
alert (number); // returns 3
I want to assign the number to a variable, so I could then make another sql query, count rows in another table, and compare the two results.
In PHP this would be:
$sql1 = mysql_query('SELECT COUNT(*) FROM table1');
$rows1 = mysql_result($sql1, 0);
$sql2 = mysql_query('SELECT COUNT(*) FROM table2');
$rows2 = mysql_result($sql2, 0);
if ($row1>$row2){}

You would be served much better by changing your query.
SELECT COUNT(ID) FROM table
Plus, its an async call so that the call return is returning the callback function. You should pass your own callback function.
function countRows(callback){
db.transaction(function (tx){
tx.executeSql('SELECT id FROM table', [], function (tx, results) {
var len = results.rows.length;
callback(len);
});
});
}

db.transaction is asynchronous. returning value isn't assigned to any variable in code above. Solution is to pass callback or create custom event, which is almost the same.
Something like this:
function countRows(cb){
db.transaction(function (tx){
tx.executeSql('SELECT id FROM table', [], function (tx, results) {
var len = results.rows.length;
cb.call(this, len);
});
});
}
countRows(function (num) {alert(num)});

Related

node-mysql how to use result outside of an anonymous function

I have a query like below:
connection.query('SELECT * FROM `Users` WHERE `Id` = ?;', [Id], function (err, row) {
var a = row;
});
//how can I use variable `a` in here?
you really won't be able to. at least not easily.
var a;
connection.query('SELECT * FROM `Users` WHERE `Id` = ?;', [Id], function (err, row) {
a = row;
});
//execute stuff
This will accomplish getting the value out into the next scope but where you would //execute stuff will have already happened before a is set. This is because (I'm assuming) node-mysql is asynchronous.

get return value from sql request

I'm currently working on a little app using phonegap and sqllite.
Filling the database works fine; but I need a function which returns me a html-string (for a id).
I have this little snippet from the internet which I "improved" for my purpose, but it doesn't work like expected :(
function getPriceFromDatabase(id) {
var result = [];
// Query the database
//
function queryDB(tx) {
tx.executeSql('SELECT * FROM PRICEFTS WHERE pid MATCH ' + id, [], querySuccess, errorCB1);
}
// Query the success callback
//
function querySuccess(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
result.push('<span class="'+results.rows.item(i).priceart+'">'+results.rows.item(i).price+'</span>');
}
}
// Transaction error callback
//
function errorCB1(err) {
console.log("Error SQL: " + err.code);
}
// Transaction success callback
//
var db = window.openDatabase("sucheDB", "1.0", "Suche DB", 52428800);
db.transaction(queryDB, errorCB1);
return result.join('');
}
Here is my sample event:
$("#price_button").click(function () {
var p = getPriceFromDatabase(88361);
console.log(p);
$('#price').html(p);
})
(I get always 'undefined' as result)
can someone help?
thanks! :)
You should provide the on-success callback to the db.transaction call, like this:
db.transaction(queryDB, errorCB1, querySuccess);
Also this function is probably async, so your return is executed before the transaction could finish.

Return executeSQL function

I'm trying to return the results of a SQL query using SQLite.
The query works fine and I can output the results inside the executeSql function. But when I try to reach the array from my main function (returnSQLArray) it is undefined.
How do I solve this problem?
I'm calling returnSQLArray inside another function where I need the results from the query.
Code:
function returnSQLArray(str)
{
var db = window.openDatabase("Database", "1.0", "Name", 200000);
var result = [];
db.transaction(
function (tx, results) {
tx.executeSql(str, [], function(tx, rs) {
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id']
}
}
console.log(result[0].id); //Returns the id
});
}
);
console.log(result[0].id); //Undefined
}
Thank you
It's an async issue. db.transaction takes a callback which executes after the sqlite transaction finishes. Your console.log() statement shown at the end of your method is actually happening before result has been populated.
EDIT ADDITION:
functions getPersons() {
returnSQLArray('SELECT * FROM PERSONS', processPersonsResponse);
}
function returnSQLArray(str, callback) {
...
tx.executeSql(str, [], function(tx, rs) { callback(result); });
}
function processPersonsResponse(response) {
//do work with response
}

Web SQL transaction does not execute properly in javascript function

I have JavaScript function that returns array of selected values from my local database.
var dataBase = {
select : selectFunction
}
var db = openDatabase(..);
var data=[ ];
function selectFunction() {
db.transaction(function (t) {
t.executeSql("SELECT * FROM Table", [], function (t, results) {
for (i = 0; i < results.rows.length; i++) {
data.push(results.rows.item(i));
}
});
});
return data;//return "stackoverflow" //works fine
}
I want to do something like this
var getSelect = dataBase.select();
alert(getSelect);
If I return string like "stackoverflow", this will work fine
alert result: stackoverflow
But if I try to return the 'data', the function returns undefined
I noticed that db.transaction is executing after the return statement, and I don't know how to fix this.
When returning results from an asynchronous function, you must use a callback, as the function will return before the actual operation has completed. You can rewrite your function like so:
function selectFunction(callback) {
db.transaction(function (t) {
t.executeSql("SELECT * FROM Table", [], function (t, results) {
for (i = 0; i < results.rows.length; i++) {
data.push(results.rows.item(i));
}
callback(data);
});
});
}
And then call it, passing a callback:
dataBase.select(function(data){
var getSelect = data
alert(getSelect);
});

Capture value from nested function in JavaScript

I have the following code snippet :
function getCheckListTaskWithId(id){
var tempTask = db.readTransaction(function (tx) {
tx.executeSql('SELECT * FROM checklisttasks where id=? ', [id], function (tx, results) {
var len = results.rows.length;
if(len>0){
var task=results.rows.item(0);
var temp= new CheckListTask(task.id,task.crud,task.name,task.status);
alert(temp);
}
});
});
}
the function that I pass to the tx.execute method is a call back function. Now I wan to return temp var present in callback function, from getCheckListTaskWithId function.
How Do I do this?
I am assuming that the executions of db.readTransaction and tx.executeSql are asynchronous. So you cannot return the result from them, as you don't know when they'll finish. The solution is use an asynchronous callback yourself. Make the getCheckListTaskWithId take a callback function as an argument and call it when result it available.
function getCheckListTaskWithId(id, callback) {
var tempTask = db.readTransaction(function (tx) {
tx.executeSql('SELECT * FROM checklisttasks where id=? ', [id], function (tx, results) {
var len = results.rows.length;
if(len > 0) {
var task=results.rows.item(0);
var temp= new CheckListTask(task.id,task.crud,task.name,task.status);
alert(temp);
callback(temp);
}
});
});
}
Rewrite tx.executeSql so it gets the return value of the callback and returns it.
This assumes that tx.executeSql doesn't perform any Ajax. Ajax is Asynchronous, so an HTTP request is made, execution continues as normal and another function is run when the request comes back. In this case it is far too late to return a value to the earlier function and anything that needs to be done with the data can only be done by the callback.

Categories

Resources