0
我發現我應該在每次使用後關閉我的遊標變量。但問題是當我試圖返回光標作爲函數的輸出。好像這是不可能的。看我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;
}
}
}
如何改變呢?
所以,如果我將光標複製到另一個變量,最後我還有一個遊標仍然打開!這有什麼問題嗎? –
請勿複製'Cursor'引用,即將其分配給另一個變量,而是循環遍歷遊標並將每行數據複製到數據結構(如「ArrayList」)。 – laalto