简体   繁体   中英

Java SQL get all rows from column

I want to get the number of rows from my database How can I create a method that returns the number of rows as an int? Here's what I got but it only returns number 1

public int getAllId() {

    SQLiteDatabase db = this.getWritableDatabase();

    int x=0;
    String where = null;
    Cursor c = db.rawQuery("SELECT COUNT (*) FROM " + TABLE_PRODUCTS, null);


     while (c.isAfterLast() == false) {



        c.moveToNext();

    }

    db.close();
    return c.getCount();

Well if you are using simple JDBC without any libraries you should be able to get the number of rows from the ResultSet I did this a while back using two approaches:

1.

    rs.last();
    rs.getRow();

2.

      int rowcount = 0;
      while (rs.next()) { 
      // more processing here 
       rowCount++;
     }

but as a word of caution, I have used this only on oracle and mysql dbs. Also if the connection is ResultSet.TYPE_FORWARD_ONLY you will not be able to go back.

you can read more about resultSets from http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

Hope this helps :)

I found the way to do it thanks to

SQLite Query in Android to count rows

Here's the code I came up with:

public int getRowCount() throws Exception {
    SQLiteDatabase db = this.getWritableDatabase();


    Cursor mCount= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_PRODUCTS,
    null); 

    mCount.moveToFirst();
    int rows= mCount.getInt(0);
    mCount.close();

return rows;

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM