Java: using a static method to get a database connection

I am working on an existing Java EE based application. To do this, use the following database connection method:

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: is the static method used correctly to connect to the database?

+5
source share
3 answers

Why did you define the function as static?

This is not wrong and there is no convention that would prevent you from invoking a static method from a non-static one. By definition, a non-static method belongs to an instance of a class, while a static method belongs to the class itself.

Having a static method simply means that you do not need an instance of the class to connect to the database.

, , , , . , ? ?

+4

, !

0

Where does initCtx come from? Since the code closes it, it seems to have its own copy. If the method creates initCtx locally (and you left the code from the example), then there seems to be no problem, but if it refers to a static variable, it will be bad. The DataSource should be thread safe (because it would not make sense).

0
source

All Articles