9

我需要计算当前在我的 sqlite 数据库中的表。尝试搜索但没有得到任何直接的方法。

我在我的 DbHelper 中尝试了这种方法。

public int countTables() {
    int count = 0;
    String SQL_GET_ALL_TABLES = "SELECT * FROM sqlite_master WHERE type='table'";
    Cursor cursor = getReadableDatabase()
            .rawQuery(SQL_GET_ALL_TABLES, null);
    cursor.moveToFirst();
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

        count++;
        getReadableDatabase().close();

    }
    cursor.close();
    return count;
}

但是这种方法给了我一个错误的计数。我的数据库中只有 3 个表,但此方法返回计数为 5。此方法可能有什么问题。有没有直接的方法来获得计数。

4

3 回答 3

23

你的方法很好,你甚至可以使用SELECT count(*) .... 但是有两个表是自动创建的android_metadatasqlite_sequence只需将这些考虑在内:5 - 2 = 您创建的 3 个表。

或者由于 Squonk 提供了关于何时sqlite_sequence创建以及何时可能存在的优秀文档,我推荐这个查询:

SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata' AND name != 'sqlite_sequence';

缩短代码的几点建议

所有这些:

cursor.moveToFirst();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

可以这样实现:

while(cursor.moveToNext()) {

如果下一行存在,则 Cursor.moveToNext() 返回 true。如果新游标不为空,moveToNext() 将返回 true 并将此索引设置在第一个位置。时cursor.isAfterLast() == true,moveToNext() 返回 false。

但是,如果您只是想计算 Cursor 中有多少行,请使用:

int count = cursor.getCount();

最后,将可写数据库存储在变量中。

getReadableDatabase().close();

我没有对此进行测试,但是如果 getReadableDatabase() 每次都返回一个新的 SQLiteDatabase 对象,那么您只需在创建此新数据库后立即关闭它...我将关闭数据库一次,然后在我关闭它之后已经关闭了我从中检索到的所有游标。

SQLiteDatabase database = getReadableDatabase();
...

database.close();

如果您使用大量查询,请考虑在 onResume() 中打开数据库并在 onPause() 中关闭它。

于 2012-07-16T14:43:43.693 回答
1

查找计数和表名

查找计数

ResultSet rs = st.executeQuery("select count(*) from sqlite_master as tables where type='table'");
System.out.println(rs.getInt(1));

检索表名

ResultSet rs2 = st.executeQuery("select name from sqlite_master as tables where type='table'");
    while(rs2.next())
    {
          String tid = rs2.getString(1);
          System.out.println(tid);
    }
    rs.close();
于 2013-12-30T05:44:14.143 回答
0

尝试

              vvvvvv
SELECT * FROM YourDataBaseName.sqlite_master WHERE type='table';

只需将您的 DatabseName 如图所示。

于 2012-07-16T14:45:06.037 回答