JNDI连接池是在comcat/conf/context.xml配置的一种连接池,依赖的jar包比较少。在context.xml 中的<Context>标签内配置:
<Resource
name="jdbc/jndipoor"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxWait="60000"
maxIdle="10"
username="scott"
password="47"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
/>
也可以配置在项目中的WEBROOT 下的 webweb-inf 中的context.xml 文件里面,如果同时配置两个地方,以comcat中的配置为主。
在Java代码中获取connection:
package test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
/**
* @author 廖滨 2014-8-11
*/
public class TestJNDI extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
Context context = null;
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
context = new InitialContext();
DataSource ds = (DataSource) context
.lookup("java:comp/env/jdbc/jndipoor");
conn = ds.getConnection();
String sql = "select * from student";
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("stuname"));
}
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}