正确的方法返回ResultSet

loc*_*zak 7 java mysql

我是java的新手,但我很快就把它拿起来了.我一直遇到的一件事是我最终得到一个充满查询和一般代码的函数,我想把它分解成单独的函数.以此为例:

public ResultSet getApples (){
    ResultSet rs;
    try{
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
        rs = stmt.executeQuery();
    } catch (SQLException e){
        e.printStackTrace();
    }
    return rs;  
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,这将是我想要做的,在一个函数中完成所有尝试和捕获,但这给了我错误: Local variable may not have been initilized

我意识到我可以做到这一点:


public function start(){
    try{
        ResultSet apples = getApples();
    catch (SQLException e){
        e.printStackTrace();
    }
}

public ResultSet getApples () throws SQLException { 
    PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
    return stmt.executeQuery();
}
Run Code Online (Sandbox Code Playgroud)

但我真的宁愿在函数内处理异常以及返回结果.

编辑 好吧,如此有条不紊地回答了提供的内容.我在这个问题上的整个目标是让我的脚本的主要功能尽可能干净.即使是额外的if ( _resultSet != null )东西也是我不喜欢的东西.话虽如此,我对这个结果非常满意:

public ResultSet getApples (){
    try{
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
        return stmt.executeQuery();
    } catch (SQLException e){
        System.out.println("************************");
        System.out.println("Class.getApples null");
        System.out.println(e.getMessage());
        return null;
    }   
}
Run Code Online (Sandbox Code Playgroud)

一切都在getApples函数内处理,当_resultSet.next()被调用时,我得到一个NullPointerException和getApples异常中的打印,所以我能够快速找到错误和调试.

evg*_*evg 3

首先将 rs 初始化为 null。

public ResultSet getApples (){
    ResultSet rs = null;
    try{
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
        rs = stmt.executeQuery();
    } catch (SQLException e){
        e.printStackTrace();
    }
    return rs;  
}
Run Code Online (Sandbox Code Playgroud)

  • 如果出现错误,您真的想返回 null 并打印到 System.out 吗?它不是很模块化。 (4认同)