lulu666 lulu666 - 6 months ago 29
MySQL Question

cursor count(*) getCount working badly

I want to check if there's a record in my table Users corresponding to an id_user, in case there isn't I will add it. The problem is that my Cursor.getCount() returns 1 and it doesn't make sense because my table is completely empty.

Cursor c = db.rawQuery("SELECT count(*) FROM Users WHERE id_user = '"
+ jsonObj.getString("id_user") + "'", null);
Log.i("getUser cursor";c.getCount() + ""); // it prints 1
c.moveToFirst();
int ic = c.getInt(0);
Log.i("getUser count2", ic + ""); // it prints 0


Why c.getCount() is giving me 1 when there is not absolutely any record. However, c.getInt(0) seems to work fine.

Thanks

Answer

Because you are getting a row back in your queury.

Select count(*) 

will return one rows containing the count of records. The count of records is 0, thus it returns one row, containing the value 0.

Select *

then

c.getCount()

Would return the 0 you are expecting because you are pulling back all rows, (not a count of rows) and there are no rows. But this is a bad approach since it can pull back extra data and might be slow.

in this case int ic = c.getInt(0); is the proper way to get the data you want.

Comments