2013-01-01 38 views
1

在我的擴展SQLiteOpenHelper的DatabaseHelper類中,我設置了各種方法將Cursors返回到其他Activities,這樣我就不會在除DatabaseHelper以外的任何其他類中執行任何查詢。在這些方法中,我不關閉遊標或數據庫之後,我回到它像:這是不好的數據庫編碼?

public Cursor getCoursesLeft() 
{ 
    // Open a readable database. 
    SQLiteDatabase database = this.getReadableDatabase(); 

    // Query the database and return the cursor. 
    return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?", 
      new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE"); 
} 

從任何活動我打電話從方法,我不保證關閉後,我用它那所返回的Cursor。

由於光標是一個對象,它應該通過引用傳遞,是否正確?因此,從其他Activity關閉它應關閉原始對象,並且如果我正確理解它,關閉Cursor也會關閉數據庫。

這是一個不好的編碼習慣?

它看起來像隨機我會得到一個LogCat錯誤,說關閉從未在數據庫上調用,我可以在我的代碼中找到唯一可能的原因是我如何返回這些方法中的遊標。

+0

作爲一個設計它是相當奇怪。通常,一個對象或圖層需要「擁有」數據庫遊標,管理它們,並且只將遊標「借」到其他圖層,或者根本不暴露它們。我會考慮從你開始的任何地方返回整個數據庫操作的結果。您還可以使用回調模式使其他類不知道遊標生命週期。 (例如,請參閱:http://static.springsource.org/spring/docs/3.0.6.RELEASE/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html) – millimoose

回答

1

如果我正確地理解它,關閉遊標也會關閉 數據庫。

這聽起來不太合適。在關閉所有遊標之後,您必須明確關閉數據庫。 logcat錯誤是由於你沒有關閉數據庫,可能試圖打開它的另一個實例。

順序很重要,首先是遊標,然後是數據庫實例。

<bad joke in 3.. 2.. 1...> 

其餘的聽起來不像任何不好的做法,當你得到分貝,你只是得到分貝它。 :d

[編輯]:你說你這樣做:

public Cursor getCoursesLeft() 
{ 
    // Open a readable database. 
    SQLiteDatabase database = this.getReadableDatabase(); 
        ^^^ here you're creating a new instance of the db 
which means the db is opened for reading, and the scope of this variable 
is lost outside this function. This means you can not close this instance explicitly 

    // Query the database and return the cursor. 
    return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?", 
      new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE"); 
} 

而是具有可以這種方法外部訪問並關閉它,一旦你做與工作數據庫變量光標(並且您已關閉光標)

SQLiteDatabase database; 
public Cursor getCoursesLeft() 
{ 
    // Open a readable database. 
    database = this.getReadableDatabase(); 

    // Query the database and return the cursor. 
    return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?", 
      new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE"); 
} 
public void someOtherFunction() { 
    Cursor blah = getCoursesLeft(); 
    // do something with blah 
    blah.close(); 
    database.close(); 
} 
+0

可以在使用之前關閉數據庫光標,會影響光標訪問數據嗎? – Emrys90

+0

從不數據庫第一。首先總是遊標,然後是數據庫實例。 – varevarao

+0

好吧,那麼當我有權訪問的數據庫實例是返回的Cursor時,如何關閉數據庫實例? – Emrys90

0

不關閉遊標只會導致內存泄漏。關閉數據庫是不同的。

關閉遊標就像關閉特定連接,以創建光標時生成的某些.file文件。

因此,您應該總是關閉您的光標。

這是不好的編碼?

不,也是。不要讓你的活動弄亂那些臨時文件。雖然沒有什麼會發生,但它似乎並不好看

+0

活動完成後,我確實關閉了光標。我得到的數據庫沒有關閉的錯誤,而不是遊標的錯誤。 – Emrys90

+0

完成數據庫後,必須運行'db.close()'方法。否則,該錯誤將顯示 – cjds

+0

我如何從當前的代碼做到這一點?我將不得不改變我如何處理返回的數據? – Emrys90

相關問題