Results 1 to 6 of 6
  1. #1
    johnmerlino is offline Member
    Join Date
    May 2014
    Posts
    56
    Rep Power
    0

    Default Passing a ResultSet but within a try/finally block

    It's always good to keep functions smaller and focused on one behavior. So is this safe:

    Java Code:
    	public Unit findBySql(int id){
    		Unit unit=null;
    		DbConnectionPool dbPool = DbConnectionPool.getInstance();
    		HashMap<String, String> conditions = new HashMap<String, String>();
    		conditions.put("id", String.valueOf(id));		
    		String sql = buildSelect("units", "*", conditions);
    		
    		Connection conn=null;
    		Statement stmt=null;
    		ResultSet result=null;
    		
    		try {
    		    conn = dbPool.getConnection();
    		    stmt = conn.createStatement();
    		    result = stmt.executeQuery(sql);
    		    
    		    if(result != null && result.isBeforeFirst()){
    				unit = create(result);
    			} else {
    				unit = createTemp(id);
    			}
    		    
    		} catch (SQLException e) {
    			Logger.writeError("Unable to create unit, so we create a temp: ");
    			Logger.writeError(e.toString());
    			unit = createTemp(id);
    		} finally {
    			try {
    				if (stmt != null)  
    	            {  
    					stmt.close();
    	            }  
    	              
    	            if (result != null)  
    	            {  
    	            	result.close();  
    	            }  
    	              
    	            if (conn != null)  
    	            {  
    	                conn.close();  
    	            }  
    			} catch(SQLException e){
    				Logger.writeError("Unable to free resource.");
    			}
    		}
    		
    		return unit;
    	}
    As you can see a pass ResultSet to a function which populates the item. But I also make sure that the ResultSet that the passed object is pointing to is closed, so it doesn't leak resources.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,955
    Rep Power
    8

    Default Re: Passing a ResultSet but within a try/finally block

    Did you have a question?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    johnmerlino is offline Member
    Join Date
    May 2014
    Posts
    56
    Rep Power
    0

    Default Re: Passing a ResultSet but within a try/finally block

    I just wanted to confirm that it wouldn't leak resources.

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,976
    Rep Power
    5

    Default Re: Passing a ResultSet but within a try/finally block

    Looks good to me, you neatly close everything there is to close and you do so in a finally clause so you are guaranteed it happens. PS: plain JDBC leads to lots of boilerplate code, please make your life a whole lot easier by creating some utility methods such as this which you can re-use:

    Java Code:
    public static void safeClose(ResultSet rs, Statement stm, Connection conn){
    
      if(rs != null){
        try{ rs.close(); } catch(Throwable t){}
      }
    
      if(stm != null){
        try{ stm.close(); } catch(Throwable t){}
      }
    
      if(conn != null){
        try{ conn.close(); } catch(Throwable t){}
      }
    }
    Note how I ignore the SQLException that close() can throw; that's because you basically can't do anything about it and if it happens, you can be pretty sure its because the database connection itself has broken down, which is something you'll certainly get in you server logs from more important places than the resource cleanup code.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,001
    Rep Power
    20

    Default Re: Passing a ResultSet but within a try/finally block

    Java Code:
    if(result != null && result.isBeforeFirst())
    The result set will never be null at this point.
    Also, it will never be anything other than before first.

    You want to actually use next() to decide whether to populate your object from the row, or to use placeholder data.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,955
    Rep Power
    8

    Default Re: Passing a ResultSet but within a try/finally block

    To eliminate some of that boilerplate code, you might use a try-with-resources: The try-with-resources Statement (The Java™ Tutorials > Essential Classes > Exceptions)
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Replies: 35
    Last Post: 12-09-2013, 07:19 PM
  2. Finally Block in Exception
    By AbbasElesgerov in forum New To Java
    Replies: 2
    Last Post: 06-01-2013, 08:25 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •