Reputation: 216
can you please tell me how to count the number
of elements in a table in sqlite
.It is not giving correct result
.
function Test(test){
alert(test)
var x;
db.transaction(function (tx) {
$yoursql = 'SELECT * FROM "'+test+'"';
tx.executeSql($yoursql, [], function (tx, results) {
alert(results.rows.length+ "rows")
x= results.rows.length+"TableName"+test;
});
return x;
});
Upvotes: 1
Views: 5351
Reputation: 283
May use this
var dBase = null;
function devicereadyFun(){
dBase = window.sqlitePlugin.openDatabase({
name: 'test.db',
location: 'default'
});
}
document.addEventListener('deviceready', devicereadyFun, false);
function Test(test){
dBase.executeSql("select count(*) as cut from "+test, [], function(rsp){
alert('Rows count in '+test+': '+rsp.rows.item(0).cut);
});
}
Upvotes: 0
Reputation: 51
var countSql = "SELECT count(*) AS cnt FROM users";
$cordovaSQLite.execute(db, countSql, []).then(function (res) {
console.log("count : " + res.rows.item(0).cnt);
});
Upvotes: 3
Reputation: 2615
You can use callBack function also..
function Test(test, callBack){
var x;
db.transaction(function (tx) {
$yoursql = 'SELECT * FROM "'+test+'" ';
tx.executeSql($yoursql, [], function (tx, results) {
x = results.rows.length + "TableName" + test;
callBack(x);
});
});
}
Call function like this..
Test('users',function(result_count){
alert(result_count);
});
Upvotes: 1
Reputation: 7063
Try this code :
function Test(test){
alert(test)
var x;
db.readTransaction(function (t) {
t.executeSql('SELECT COUNT(*) AS c FROM ' + test, [], function (t, r) {
alert(r.rows[0].c + "rows")
x= r.rows[0].c+"TableName"+test;
});
});
return x
}
I replaced db.transaction
with db.readTransaction
, added a COUNT(*) AS c
instead of *
and so I replaced results.rows.length
with r.rows[0].c
. For more information, you can have a look to the W3C documentation.
Upvotes: 1