Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java : Using Static Method for obtaining Database Connection

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?

like image 927
Pawan Avatar asked Jul 13 '12 13:07

Pawan


1 Answers

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?

like image 61
Chris Dargis Avatar answered Oct 12 '22 23:10

Chris Dargis