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?

4

2 回答 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?

于 2012-07-13T14:06:13.777 回答
0

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

于 2012-07-13T14:15:45.280 回答