ANDROID: Finding the size of individual tables in

2019-05-07 15:30发布

问题:

I am trying to do something along the following lines:

SELECT bytes from user_segments where segment_name = 'TABLE_NAME';

I know that I can get the size of the whole database by

mDb = SQLiteDatabase;
long size = new File(mDb.getPath()).length();

Is it possible to get how much space an individual table takes up in storage in Android's SQLiteDatabase?

EDIT--

By the lack of response, I guess that it's not possible with SQLite. I am currently using a hack-ish way where I count the number of rows in the table and estimate how much space a single row takes (based on the given table schema).

回答1:

If you mostly store binary or string data in a single column, you can use an aggregate query:

SELECT SUM(LENGTH(the_column)) FROM the_table

This can give you a reasonable estimate even when the size of each row varies a lot (for example if you store pictures in the database). However, if you have many columns with a small amount of data in each, your approach (estimating a fixed size per row) is better.

On Android, you can implement it like the following:

SQLiteDatabase database = ... // your database
// you can cache the statement below if you're using it multiple times
SQLiteStatement byteStatement = database.compileStatement("SELECT SUM(LENGTH(the_column)) FROM the_table");
long bytes = byteStatement.simpleQueryForLong();