Android的SQLite的光标出的SELECT COUNT(*)FROM表越界异常 [英] Android SQLite Cursor out of bounds exception on SELECT count(*) FROM table

查看:530
本文介绍了Android的SQLite的光标出的SELECT COUNT(*)FROM表越界异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数是给我一个出界异常...

The following function is giving me an out of bounds exception...

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}

它的意思返回在数据库中的行数。任何人都知道什么是错了吗?我也许我完成这个任务的方法不对?

It's meant to return the number of rows in the database. Anybody know whats wrong? am I perhaps doing this task the wrong way?

推荐答案

您错过了

mcursor.moveToFirst();

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}

但是,你应该用更好的方法完成这个任务,就像DatabaseUtils的内置助手

But you should use better methods for this task, like the inbuilt helpers of DatabaseUtils

public long count() {
    return DatabaseUtils.queryNumEntries(db,'tablename');
}

您可能会发现有助于使用 DatabaseUtils.longForQuery()拿到第一列长值,当你在哪里查询的总数。它的简单,你不需要是一堆工作的光标。

You might find helpful to use DatabaseUtils.longForQuery() to get the first column long value, when you have where query for the total count. It's simpler and you do not need that bunch of work with the Cursor.

这篇关于Android的SQLite的光标出的SELECT COUNT(*)FROM表越界异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆