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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With