I have set up jdbc connection pooling in a java-ee environment by doing the following changes.
The context.xml
<Context>
<Resource name="jdbc/mysybase" auth="Container"
type="javax.sql.DataSource" driverClassName="com.sybase.jdbc3.jdbc.SybDriver"
url="jdbc:sybase:Tds:H2S33.studtrack.com:2025/student"
username="scott" password="tiger" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>
In The web.xml file
<resource-ref>
<description>Sybase Datasource example</description>
<res-ref-name>jdbc/mysybase</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
And the jsp page
<%@page import="java.sql.*"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="javax.sql.DataSource"%>
<html>
<head>
<title>Obtaining a Connection</title>
</head>
<body>
<%
Connection conn = null;
ResultSet result = null;
Statement stmt = null;
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/mysybase");
conn = ds.getConnection();
if (conn != null)
{
String message = "Got Connection " + conn.toString() + ", ";
out.write(message);
}
else
{
out.write("hello no conn obtained");
}
stmt = conn.createStatement();
result = stmt.executeQuery("SELECT * FROM Student");
while(result.next())
{
out.write(result.getString("name"));
}
}
catch (SQLException e) {
out.write("Error occurred " + e);
}
%>
</body>
</html>
Now i want the jdbc pooling to be available in normal java classes as well.
Do i need to make any changes if i want the pooling to be available in java classes.
Can i get a connection object in a java class just as i got the connection in the jsp as shown above.
Connection conn = null;
ResultSet result = null;
Statement stmt = null;
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/mysybase");
conn = ds.getConnection();
1.) You can set a contextListener to initialize connection only once and get logical conn from the pool (gues you use tomcat’s DBCP).
2.) Yes, once you start a connection (driver sets a socket and the pool gets initialized) from context data, you can get a connection (from the pool) properly invoking that from any java class.
3.) Try not to put pure Java code in JSPs. Just a rule of the road: is treated as a poor decision.