通过执行以下更改,我在java-ee环境中设置了jdbc连接池。JDBC连接池清理
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>
现在我想要jdbc池在正常的java类中也可用。 我是否需要进行任何更改,如果我想在Java类中提供池化。 我可以在java类中获得连接对象,就像我在上面显示的jsp中的连接一样。
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();
因此,即使我为jsp/servlets设置了jdbc pooling,你的意思是我可以在纯java类中使用这个池,以及我在jsp/servlets中使用的池。 – 2012-02-08 04:40:01
当您在上下文中设置数据源时,可以在上下文初始化时使用它(例如,将其添加到会话中)。这里解释contextListener的想法,在那里你可以添加到会话的conn实例http://www.roseindia.net/servlets/ServletContextListener-example.shtml – Alfabravo 2012-02-08 04:51:21
我想在纯java类中使用jdbc连接池而不是在servlet中。 – 2012-02-08 07:06:13