G'day,

I'm just looking to clean up some of my code as i know that at the moment it doesnt follow the best practices. I have the following function which calls my database() class. I know that i need to close my connections and statements im just not too sure how to do it.

If anyone could provide a quick syntax as to how i could set my functions out I'd be very much appreciative.

My current function syntax;

public boolean function(String valueOne, int valueTwo ){
	try{
		Connection connect = new database().getConnection();
        	Statement con = connect.createStatement();

		String qry = "SELECT * FROM table";
		ResultSet res = con.executeQuery(qry);

		// Do i close the connection and statement here??
	}catch(SQLException ex){
            ex.printStackTrace();
        }

	// OR here??
        
        return added;
}

Regards,
TC

The fastest way is do it as

public boolean function(String valueOne, int valueTwo ){
    Connection connect = null;
	try{
		connect = new database().getConnection();
        	Statement con = connect.createStatement();

		String qry = "SELECT * FROM table";
		ResultSet res = con.executeQuery(qry);

		// Do i close the connection and statement here??
	}catch(SQLException ex){
            ex.printStackTrace();
        }

	try{
            connect.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
        
        return added;
}

If I use the resultset and connection and done with them in sing function then I would close them in finally body

Not a good idea Effective Java by Joshua Bloch - chapter 2 Creating and destroying objects - Item 7 : Avoid finalizers (unfortunately 2 pages are omitted as this is only limited preview)

EDIT:
Safari reference

Edited 6 Years Ago by peter_budo: n/a

This article has been dead for over six months. Start a new discussion instead.