6

I am working on an existing Java EE based application. This features the following method for connecting to a database :

public static java.sql.Connection connectionToDataBase(String jndiName,boolean flag)throws Exception 
{
DataSource ds =(javax.sql.DataSource) initCtx.lookup(jndiName);
return ds.getConnection();
    } catch (NamingException ne) {
            throw ne;
        } finally {
            try {
                if (initCtx != null)
                    initCtx.close();
            } catch (NamingException ne) {

                throw ne;
            }
        }
}

My question is whether using a static method for connecting to a database is correct?

5
  • 2
    There is nothing wrong with using a static method to connect to a database. Commented Jul 13, 2012 at 13:59
  • 5
    Are you catching (line 5) without trying? Commented Jul 13, 2012 at 13:59
  • I did not posted the whole method code , so some part might is missing , the only intention of this question is using Static Method for getting DB Connection is valid or not . Commented Jul 13, 2012 at 14:07
  • 1
    @gobernador: That's not quite true. The finally block will alway run. (see the JLS) Commented Jul 13, 2012 at 14:11
  • @ig0774 You're right, I didn't know that. Well, you learn something every day. Commented Jul 13, 2012 at 14:13

2 Answers 2

4

Why have you defined the function as static?

It is not incorrect nor is there any convention that would prohibit you in calling a static method from a non-static one. By definition, a non-static method belongs to an instance of the class, whereas a static method belongs to the class itself.

Having a static method simply means you don't need an instance of the class to connect to the DB.

To answer your question, you probably want to consider what the class encapsulates. Do you only want an instance of the class to be able to connect to the DB? Or would you like to be able to connect to the DB without a reference to an instance of the class?

Sign up to request clarification or add additional context in comments.

Comments

0

If you can use a Connection-Pool or an Entity-Manager you better use them!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.