java-jndi(tomcat-oracle)

本文介绍如何通过在META-INF下添加context.xml文件配置Oracle数据库连接池,并在WEB-INF下的web.xml中引用,最后展示了如何在index.jsp页面使用JNDI获取连接池资源并查询数据。

步骤一、META-INF下添加context.xml

 

<?xml version="1.0" encoding="UTF-8"?>
 <Context> 
 <Resource name="jdbc/oracle" auth="Container"    
        type="javax.sql.DataSource"        
        maxActive="100" maxIdle="30" maxWait="5000" username="test"    
        password="test" driverClassName="oracle.jdbc.driver.OracleDriver"    
        url="jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> 
</Context>

 

步骤二、WEB-INF下web.xml中添加

 <resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/oracle</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
  </resource-ref>

 

步骤三、在index.jsp

<%@ page import="java.sql.*,javax.sql.*,javax.naming.*" %>

 

 <body>中添加如下代码:

<%
    ResultSet rSet=null;
    PreparedStatement ps=null;
    Connection conn=null;
    String sqlString=null;
    try {
      Context ctx=new InitialContext();
      DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
      conn=ds.getConnection();
      sqlString="select a,b from testa";
      ps=conn.prepareStatement(sqlString);
      rSet=ps.executeQuery();
      out.print("<Table Border>");
      out.print("<TR>");
      out.print("<TH width=100>"+" 学号");
      out.print("<TH width=100>"+" 姓名");
      out.print("</TR>");
      while(rSet.next())
      {
        out.print("<TR>");
        out.print("<TD >"+rSet.getString(1)+"</TD>");
        out.print("<TD >"+rSet.getString(2)+"</TD>");
        out.print("</TR>") ;
       }
        out.print("</Table>");
         } catch (Exception e) {
          e.printStackTrace();    
          }finally{
          ps.close();
          rSet.close();
          conn.close();
     }
%>

 

步骤四、oracle数据库中建表

create table TESTA
(
  A VARCHAR2(10),
  B VARCHAR2(50)
);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值