I am using a Java web application on a Tomcat server and would like to know what is the "best practice" in terms of accessing a database connection from Tomcat JNDI?
Currently, this is basically what I do every time I need to access the database:
Context envContext = null;
DataSource dataSource = null;
try {
envContext = (Context)ctx.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/datasource");
return dataSource.getConnection();
} catch (Exception e){
e.printStackTrace();
return null;
}finally {
if(envContext != null){
try{
envContext.close();
} catch (NamingException e){
e.printStackTrace();
}
}
}
However, is this the right way to find a connection to JNDI every time I want to access a database? Should I refer instead to a Context or data source?
source
share