成语关闭游标 [英] Idiom to close a cursor

查看:187
本文介绍了成语关闭游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下哪两个,我应该使用,以确保所有的游标都关闭?

Which of the following two should I be using to make sure that all the cursors are closed?

    Cursor c = getCursor(); 

    if(c!=null && c.getCount()>0){ 
        try{ 
            // read values from cursor 
        }catch(..){} 
        finally{ 
            c.close(); 
        } 
    }//end if

    OR

    Cursor c = getCursor(); 
    try{ 
        if(c!=null && c.getCount()>0){ 
            // read values from cursor 
        }//end if 
    }catch(..){

    }finally{ 
        c.close(); 
    } 

编辑:
几个问题:
1.我们需要调用close()上的光标,其具有0计数?
2.因为在这种情况下,第成语,close()方法将永远不会被调用。它假设为无元素的光标,光标将永远不会被打开。这是一个有效的假设?


A few questions:
1. Do we need to call close() on a cursor which has count of 0?
2. Because in that case for the first idiom, close() will never be called. It assumes that for a cursor having no elements, cursor will never be opened. Is this a valid assumption?

请指教。

推荐答案

都不是,但第二个是最接近的。

Neither, but the second one was closest.

  • 选项1不正确关闭 游标时getCount将()== 0
  • 选项2叶finally块暴露在空指针异常
  • Option 1 doesn't properly close the Cursor when getCount() == 0
  • Option 2 leaves the finally block exposed to a null pointer exception

我会用:

Cursor c = getCursor(); 
try { 
    if(c!=null && c.getCount()>0){ 
         // do stuff with the cursor
    }
}
catch(..) {
    //Handle ex
}
finally { 
    if(c != null) {
        c.close(); 
    }
}

...或者,如果你希望光标为null频繁,你可以把它在它的头一点点:

... or if you expect the cursor to be null frequently, you could turn it on its head a little bit:

Cursor c = getCursor(); 
if(c != null) {
    try { 
        if(c.getCount()>0) { 
             // do stuff with the cursor
        }
    }
    catch(..) {
        //Handle ex
    }
    finally { 
        c.close(); 
    }
}

这篇关于成语关闭游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆