1

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;
});
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
Ravi Aaaaaa
  • 216
  • 5
  • 12

4 Answers4

3
var countSql = "SELECT count(*) AS cnt FROM users";
$cordovaSQLite.execute(db, countSql, []).then(function (res) {
    console.log("count : " + res.rows.item(0).cnt);
});
1

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.

Lucas Willems
  • 6,673
  • 4
  • 28
  • 45
1

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);
});
Sunil Dodiya
  • 2,605
  • 2
  • 18
  • 21
0

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);
    });
}
Om Shankar
  • 265
  • 4
  • 11