我正在尝试在查询中进行查询
id = mCursor.getInt(mCursor.getColumnIndex(DatabaseHelper.COLUMN_SUBJECT_ID));
S = new Subject(id, getSubjectDescById(id));
Subjects.add(S);
getSubjectDescById()函数自己打开另一个游标。 mCursor在代码之前打开并在之后关闭。 嵌套游标有风险吗?如果是这样,那么什么是我的代码的更好的替代
答案 0 :(得分:2)
<强> I have not tested this though but i think,Yes you can use Nested cursors
强>
Scenario
:
Step-1>
打开CURSOR-1 Step-2>
打开CURSOR-2并将该光标用作您想要创建的新光标的指针Step-3>
关闭CURSOR-2 Step-4>
关闭Cursor-1 试试此示例 ::
private void DemoFunction() throws Exception {
DatabaseHandler mHelper;
SQLiteDatabase db = null;
Cursor mCursor1 = null;
Cursor mCursor2 = null;
try {
mHelper = new DatabaseHandler(getActivity());
db = mHelper.getReadableDatabase();
//make query for buffet-type
mCursor1 = db.rawQuery("<------My First Query ------>", null);
if(mCursor1.moveToFirst()){
do{
mCursor2 = db.rawQuery("<------My Second Query ------>", null);
if(mCursor2.moveToFirst()){
do{
}while(mCursor2.moveToNext());
Log.d("", "");
}
}while(mCursor1.moveToNext());
Log.d("", "");
}
} catch (Exception e) {
if(isErr==false){
errMsg=e.getLocalizedMessage();
isErr=true;
}
throw e;
}finally{
if(db!=null){
if(db.isOpen()) db.close();
}
if(mCursor1!=null||mCursor2!=null){
if(!mCursor2.isClosed())mCursor2.close();
if(!mCursor1.isClosed())mCursor1.close();
}
}
}
注意 : - 确保关闭所有游标