Proper way to return a ResultSet
我是Java的新手,但是很快就可以使用它。我一直碰到的一件事是,我最终拥有了一个充满查询的功能,并且只是一般的代码,我想将其分解为单独的功能。以这个为例:
1 2 3 4 5 6 7 8 9 10 | 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; } |
理想情况下,这就是我想要做的,在一个函数中包含所有的try和catch,但这给了我错误:
我确实知道我可以这样做:
1 2 3 4 5 6 7 8 9 10 11 12 | 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(); } |
但是我真的希望在函数中处理异常并返回结果。
编辑
好吧,这是对所提供内容的修改后的答案。我在此问题上的全部目标是使脚本的主要功能尽可能简洁。我什至不喜欢多余的
1 2 3 4 5 6 7 8 9 10 11 | 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; } } |
一切都在
你可以这样声明你的RS
1 |
但是在调用函数的位置:
1 |
您必须检查:
1 2 3 4 | if(apples == null) { //do something, because your query did not work. } |
首先将rs初始化为null。
1 2 3 4 5 6 7 8 9 10 | 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; } |
因为您没有将ResultSet rs设置为任何初始值。最后,您要归还它。
如果发生任何异常并且rs值未设置值该怎么办。为了解决这个问题,您需要在声明时为rs分配空值。
我在第一个示例中看到的最大问题(除了未初始化
确保所有这些事情发生的一种非常好的方法是使用Spring的JDBCTemplate(更多文档在这里)。这将为您处理所有连接管理详细信息。您只需编写您的SQL和代码来处理
您可以使用CachedRowSet。有关详细的答案,您可以在这里查看我的答案