簡體   English   中英

我應該關閉本地數據庫游標嗎?

[英]Should I close local database cursor?

我的代碼如下所示:

public static synchronized String getPreferenceString(Context context, String key)
    {
        Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[]{ "Value" }, "Key=?", new String[]{ key }, null, null, null, null);

        if (c.getCount() == 0)
        {
            c.close();
            return "";
        }

        c.moveToFirst();
        String retVal = c.getString(0);
        c.close();

        return retVal;
    }

基本上,我從數據庫表中獲得了特定的價值。 效果很好,但是我想整理一下我的代碼,所以它看起來像這樣:

public static synchronized String getPreferenceString(Context context, String key)
    {
        Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[]{ "Value" }, "Key=?", new String[]{ key }, null, null, null, null);

        if (c.getCount() == 0) return "";

        c.moveToFirst();
        return c.getString(0);
    }

可以,還是應該關閉這些游標?

    public static synchronized String getPreferenceString(Context context, String key)
    {
        Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[] { "Value" }, "Key=?",
                new String[] { key }, null, null, null, null);

        if (c == null)
             return "";

        try {    
            return c.moveToFirst() ? c.getString(0) : "";
        } finally {
            c.close();
        }
    }

除非應用程序以某種方式對其進行管理,否則您應該始終關閉光標(帶有加載程序的Android automagic工具等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM