I am new to java, but I quickly pick it up. One thing that I continue to encounter is that I have one function full of queries and all the code in general, and I would like to break it down into separate functions. Take this for example:
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; }
Ideally, this will be what I want to do, all attempts and catches within the same function, but it gives me an error: Local variable may not have been initilized
I understand that I can do this:
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(); }
But I would really prefer the exceptions to be thrown inside the function, and also return the result.
EDIT Well, as curious as possible. My goal in this matter was to make the main functions of my script as clean as possible. Even the extra if ( _resultSet != null ) was something I didn't like. However, I am very pleased with this result:
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; } }
Everything is handled in the getApples function, and when _resultSet.next() is called, I get a NullPointerException and fingerprints in the getApples exception, so I can quickly find the error and debug it.
locrizak
source share