I’m just getting to grips with Tomcat and mySQL using the resource sharing method. Its all working fine, but I don’t think I’m handling the connection right. I’m used to using JDBC direct to MySQL not on Tomcat.
My servlet calls intializeConnection() when it is first run, and never again. But I think that I should actually open and close the connection on each statement? Could someone adjust the code below to show the correct method of handling the connection, I’m a little confused.
public Connection con;
public void intializeConnection() throws SQLException, NamingException{
connect();
}
public void connect() throws SQLException, NamingException{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
con = ds.getConnection();
}
public void excuteStatement(String query) throws SQLException{
con.createStatement().executeUpdate(query);
}
public ResultSet getResultSet(String query) throws SQLException{
//not yet implemented
}
My second question is, I don’t know how to return a resultSet this way?
TIA
I think a better design is to use a connection for each request and close it when you’re done. It’ll scale better, in my opinion.
Have a look at the JDBC tutorial. It’ll show you how to get a ResultSet and much more:
http://docs.oracle.com/javase/tutorial/jdbc/basics/