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