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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.