Scope of Connection Object for a Website using Connection Pooling (Local or Instance)
Posted
by
Danny
on Stack Overflow
See other posts from Stack Overflow
or by Danny
Published on 2010-02-09T00:41:46Z
Indexed on
2010/12/26
1:54 UTC
Read the original article
Hit count: 554
For a web application with connection polling enabled, is it better to work with a locally scoped connection object or instance scoped connection object. I know there is probably not a big performance improvement between the two (because of the pooling) but would you say that one follows a better pattern than the other. Thanks ;)
public class MyServlet extends HttpServlet {
DataSource ds;
public void init() throws ServletException {
ds = (DataSource) getServletContext().getAttribute("DBCPool");
}
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
SomeWork("SELECT * FROM A");
SomeWork("SELECT * FROM B");
}
void SomeWork(String sql) {
Connection conn = null;
try {
conn = ds.getConnection();
// execute some sql
.....
} finally {
if(conn != null) {
conn.close(); // return to pool
}
}
}
}
Or
public class MyServlet extends HttpServlet {
DataSource ds;
Connection conn;*
public void init() throws ServletException {
ds = (DataSource) getServletContext().getAttribute("DBCPool");
}
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
try {
conn = ds.getConnection();
SomeWork("SELECT * FROM A");
SomeWork("SELECT * FROM B");
} finally {
if(conn != null) {
conn.close(); // return to pool
}
}
}
void SomeWork(String sql) {
// execute some sql
.....
}
}
© Stack Overflow or respective owner