【问题标题】:When should I close cursor variable?我应该什么时候关闭游标变量?
【发布时间】:2017-02-03 18:40:01
【问题描述】:

我发现每次使用后我都应该关闭游标变量。但问题是当我试图将光标作为函数的输出返回时。似乎这是不可能的。看看我试图在我的函数中关闭光标和数据库的 DbHelper:

公共类 DbHelper 扩展 SQLiteOpenHelper{

public DbHelper(Context context) {
    super(context, "shareholders.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        String sql = "CREATE TABLE IF NOT EXISTS news (id integer,title text,description text,sDate text)";
        db.execSQL(sql);
        sql = "CREATE TABLE IF NOT EXISTS cities (id integer,name text)";
        db.execSQL(sql);
    } catch (Exception e) {
        xLog.error(e.getMessage());
    }
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    // TODO Auto-generated method stub

}

public long insert(String table,ContentValues cv){
    SQLiteDatabase mydb =this.getWritableDatabase();
    long result=-1;
    try {
        result = mydb.insert(table,null, cv);
        }catch (Exception e) {
        xLog.error(e.getMessage());
    }
    finally{
        mydb.close();
    }
    return result;
}

public Cursor selectAll(String table){
    SQLiteDatabase mydb =this.getReadableDatabase();
    String sql = "SELECT * FROM "+table;
    xLog.info(sql);
    Cursor result=null;
    try {
        result = mydb.rawQuery(sql, null);
    } catch (Exception e) {
        xLog.error(e.getMessage());
    }
    finally{
        result.close();
        mydb.close();
    }
    return result;
}

public Cursor select(String table,String where){
    SQLiteDatabase mydb =this.getReadableDatabase();
    String sql = "SELECT * FROM "+table+" WHERE "+where;
    xLog.info(sql);

    Cursor result=null;
    try {
        result = mydb.rawQuery("SELECT * FROM "+table+" WHERE "+where, null);
    } catch (Exception e) {
        xLog.error(e.getMessage());
    }
    finally{
        result.close();
        mydb.close();
    }
    return result;
}

public long update(String table,ContentValues cv,String condition){
    SQLiteDatabase mydb =this.getWritableDatabase();
    long result = -1;
    try {
        result = mydb.update(table, cv, condition, null);
    } catch (Exception e) {
        xLog.error(e.getMessage());
    }
    finally{
        mydb.close();
    }
    return result;
}

}

}

怎么改?

【问题讨论】:

    标签: android android-cursor sqlite


    【解决方案1】:

    您应该在使用完Cursor 后关闭它。如果您将 Cursor 返回给调用者,您还没有完成。

    一些选项:

    • 收到Cursor 的调用者负责关闭它。

    • 您的函数将数据从Cursor 复制到某个其他数据结构,关闭游标并返回复制的数据。

    【讨论】:

    • 因此,如果我将光标复制到另一个变量中,最后我仍然打开了一个光标!这有什么问题吗?
    • 不要复制Cursor引用,即分配给另一个变量,而是循环游标并将每一行数据复制到一个数据结构中,例如ArrayList。
    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2012-12-23
    • 2021-07-13
    • 2021-09-07
    相关资源
    最近更新 更多