Hi all,
have free time when to understand some basic concept in java . in my code I use
public void init() throws ServletException {
Context env = null;
try {
env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/CampusLife");
if (pool == null) {
throw new ServletException(
"'jdbc/db' is an unknown DataSource");
}
} catch (NamingException ne) {
throw new ServletException(ne);
}
}
public synchronized Connection getConnection()
throws SQLException, ServletException {
Connection conn = null;
try {
conn = pool.getConnection();
} catch (SQLException sqle) {
System.out.println("JDBC error:" + sqle.getMessage());
sqle.printStackTrace();
throw sqle;
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
conn = null;
}
return conn;
}//end connection
late in my get or post I use conn = pool.getConnection(); to do my job, I want to create a sharable connection object . I Google , it looks like after 2005 only a few article mention about connection pool and Singleton, even you did found some is about load the JDBC driver and very complicit code. so is create an object to share withe every servlet is an good idea or not ?
I try to do the following ,but not work yet
package Connection;
import javax.servlet.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
/**
*
* @author root
*/
public class MyConnection {
Context env = null;
DataSource pool;
public MyConnection() throws ServletException {
try {
env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/CampusLife");
if (pool == null) {
throw new ServletException(
"'myDataPool' is an unknown DataSource");
}
} catch (NamingException ne) {
throw new ServletException(ne);
}
}
public synchronized Connection getConnection() {
Connection conn = null;
try {
conn = pool.getConnection();
} catch (Exception exception) {
System.err.println("getConnection (): " + exception.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e1) {
e1.printStackTrace();
}
conn = null;
}
return conn;
}//end connection
}
in my servlet
public void init(){
try {
pool = new MyConnection();
} catch (ServletException ex) {
Logger.getLogger(download.class.getName()).log(Level.SEVERE, null, ex);
}
}
please advice?