繁体   English   中英

计算android sqlite表中的列数

[英]Counting no of columns in an android sqlite table

嗨,我想计算android sqlite表中的总列数,请指导该如何实现? 我尝试的是下面

    public int numberOfColumns(String tableName) {


    Cursor cursor = database.query(tableName, null, null, null, null, null, null);

    if (cursor != null) {
        if (cursor.getColumnCount() > 0) {
            return cursor.getColumnCount();
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

这很好,我想知道的是,这种方法很好,或者我可以做得更好! 我访问了很多stackoverflow链接,但仍然感到困惑。

这可行。 还有其他一些方法,例如PRAGMA table_info(tablename)但实际上并没有那么好。

不需要检查cursor != null

另外,最好在退出方法之前关闭光标。

离开函数后,您需要关闭光标,此更改应该起作用(未经测试)

public int numberOfColumns(String tableName) {
    int result = 0;
    Cursor cursor = null;
    try {
        cursor = database.query(tableName, null, null, null, null, null,
                null);
        result = cursor.getColumnCount();
        if (result < 0) {
            result = 0;
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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