【问题标题】:Can't get any results using query/rawquery #SQLite#使用查询/原始查询#SQLite#无法获得任何结果
【发布时间】:2012-04-06 15:23:13
【问题描述】:

当我使用下面的代码查询数据库时,我无法获得任何结果,但我可以通过控制台上的 sql 命令获得结果。

DBHelper dbHelper = new DBHelper(SampleActivity.this, "contents.db", null, 1);
SQLiteDatabase db = dbHelper.getWritableDatabase();
//Cursor cursor = db.query("ContentsTable", new String[] { "title" }, "id<10", null, null, null, null);
Cursor cursor = db.rawQuery("select title from ContentsTable", null);
db.close();
cursor.close();

我调试程序,运行db.rawquery(*)后发现cursor的mCount=-1,mStackTrace=DatabaseObjectNotClosedException,如图所示:http://flic.kr/p/bw9P2o

下面是 DBHelper 类: 公共类 DBHelper 扩展 SQLiteOpenHelper{

    public DBHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "create table ContentsTable(id int, title varchar(100))";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("Update Database");
    }

}

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    请原谅这个简单的问题,但您添加行了吗?

    编辑:

    您必须在访问返回的数据之前调用cursor.moveToFirst()

    【讨论】:

    • 是的,因为我可以通过控制台上的 sqlite3 命令(从 ContentsTable 中选择标题)获得结果
    • 好的,先关闭游标再关闭db。或者更好的是尝试在您的活动中使用 startManagingCursor() 而不必担心关闭它。
    • 运行后得到所有信息:Cursor cursor = db.rawQuery("select title from ContentsTable", null);不运行 db.close() 或 cursor.close();
    • 这可能更适合作为评论...不是答案
    • @AlexLockwood 我同意,但没有足够的代表来评论问题本身......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2011-04-10
    • 2014-04-09
    • 2021-05-08
    • 1970-01-01
    • 2021-10-12
    • 2014-02-25
    相关资源
    最近更新 更多