JAVA实现JNDI连接数据库

第一步:实现一个Java类:

package com.citichy.fileupload.property;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.sql.Date;
public class Test{
  private Connection con;
  private Statement stmt;
  private ResultSet rs;
  private PreparedStatement pstmt;
  public static int error=0;
  public static synchronized Connection getCon()throws Exception{
     Context ctx;
     DataSource ds;
     try{
      ctx = new InitialContext();
      ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DBPool");
      if(ds==null){
       System.err.println();
       System.err.println("数据连接打开+"+(++error));
      }
      return ds.getConnection();
     }catch(SQLException e){
      System.out.println(e);
      throw e;
  }catch(NamingException e){
      System.out.print(e);
      throw e;
  }
   }
 
 public Statement getStmtread(){
  try{
   con=getCon();
   stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
  }catch(Exception e){
   System.out.println("getStmtread");
   System.out.println(e.getMessage());
  }
  return stmt;
 }
 
public int getRowCount(String sql){
 int count=0;;
 try{
  stmt=this.getStmtread();
  rs=stmt.executeQuery("SELECT COUNT(*) FROM "+sql);
  rs.getMetaData();
  if(rs.next()){
   count=rs.getInt(1);
  }else{
   count=-1;
  }
 }catch(Exception e){
  System.out.println("getRowCount");
  System.out.println(e.getMessage());
  count=-2;
 }finally{
  this.close();
 }
  return count;
 }
 
 public Statement getStmt(){
  try{
   con=getCon();
   stmt=con.createStatement();
  }catch(Exception e){
   System.out.println("getStmt");
   System.out.println(e.getMessage());
  }
  return stmt;
 }
 
 
 public PreparedStatement getPstmt(String sql){
  try{
   con=getCon();
   pstmt=con.prepareStatement(sql);
  }catch(Exception e){
   System.out.println("getPstmt");
   System.out.println(e.getMessage());
  }
  return pstmt;
 }
  
 public void close(){
  try{
  if(rs!=null)rs.close();
   }catch(Exception e){
   }
   try{
    if(stmt!=null)stmt.close();
   }catch(Exception e){
   }
   try{
    if(con!=null){
     con.close();
     con=null;
     System.err.println();
     System.err.println("数据连接关闭-"+(--error));
    }
   }catch(Exception e){
    System.out.println("close");
    System.out.println(e.getMessage());
   }
 }
 
 public String inStr(String str){
  String tempstr=null;
   if(str==null){
    str="";
   }else{
    try{
     tempstr=new String(str.getBytes("ISO-8859-1"),"GB2312");
    }catch(Exception e){
     System.out.println(e.getMessage());
    }
   }
  return tempstr;
 }
  
 public String outStr(String str){
  if(str==null){
   str="";
  }else{
   try{
    str=str.replace((char)1,'\'');
   }catch(Exception e){
    System.out.println("outStr");
    System.out.println(e.getMessage());
   }
  }
  return str;
 }
  
 public int selectdata(String sqls){
  int k=-10;
  try{
   k=0;
   rs=this.getStmtread().executeQuery(sqls);
   while(rs.next()){
    k++;
   }
  }catch(Exception ex){
   k=-1;
   System.out.println("select");
   System.out.println(ex.getMessage());
   this.close();
  }finally{
   this.close();}
   return k;
 }
 
 public int updata(String sqls){
  int k=-10;
  try{
   k=0;
   k=this.getStmt().executeUpdate(sqls);
  }catch(Exception ex){
   k=-1;
   System.out.println("updata");
   System.out.println(ex.getMessage());
   this.close();
  }finally{this.close();}
   return k;
 }
  
  
 public Date StrConvertDate(String strdate{ 
  Date convertdate=null;
  try{   
   convertdate= Date.valueOf(strdate);
   System.out.print("打印日期");
   System.out.print(convertdate.toString());
  }catch(Exception ex){ex.printStackTrace();}
   return convertdate;
  }
}
 
 
 //接下来是重点,也就是getCon()是如何获取到连接的
 
 //第二部:配置web.xml文件
 
   <!-- JNDI -->
   <resource-ref>
     <description> MySQL DB Connection Pool </description>
     <res-ref-name> jdbc/DBPool </res-ref-name>
     <res-type> javax.sql.DataSource </res-type>
     <res-auth> Container </res-auth>
     <res-sharing-scope> Shareable </res-sharing-scope>
   </resource-ref>
 
 红色字体与Java文件中的必需一致,编译时时通过这些描述符来实现映射
 java:comp/env/jdbc/DBPool(虚地址)   ------>    映射描述符   ------>       jdbc/DBPool(实际的地址)
 单单这样子还是不够的,在Tomcat中还需要和该web.xml文件建立连接
 
 
 
// 第三步:配置Tomcat目录下conn文件夹中的context.xml配置文件
 
 在<Context>
 
   <Resource
     name="jdbc/DBPool"
     type="javax.sql.DataSource"
     password=""
     driverClassName="com.mysql.jdbc.Driver"
     maxIdle="20"
     maxWait="5000"
     username="root"
     url="jdbc:mysql://localhost:3306/logistic"
    />
 
 </Context>
 
 以上是以MySql作为数据库,如果用其他数据库,改变url和driverClassName即可,但必需保证用户名、密码正确。
 完成以后,还要将连接数据库的jar包,放在    Tomcat6/lib    目录下,而  Tomcat6/bin  下不需要放此jar包 。
 
 可能有的网友调试的时候会报这个错误:
  javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter,  or in an application resource file:  java.naming.factory.initialException in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
  at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
  at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
  at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
  at javax.naming.InitialContext.lookup(InitialContext.java:392)
  at gzgl.DataConnect.getCon(DataConnect.java:31)
  at gzgl.DataConnect.main(DataConnect.java:23)
 
 这是因为通过JNDI获取连接,程序必须通过Tomcat容器来加载连接,即通过web.xml来建立连接,如果只是在Java代码里面测试,是无法获取到连接的,因此,可以通过JSP(如index,jsp里面)进行如下测试:
 
 <%@ page language="java"  pageEncoding="UTF-8"%>   
 <
%@page contentType="text/html; charset=UTF-8"%>   
 <
%@page import="java.sql.*" %>   
 <
%@page import="javax.naming.*" %>   
 <
%@page import="javax.sql.DataSource" %> 
 <
%@page import="com.logistic.data.*" %> 
 <head>   
 <title>Tomcat6.0 JNDI!</title>  
 </head>  
     
   <body>   
     This is my JSP page. <br>   
     JNDI ... <br>   
 <%   
 try {    
    DataConnect.getCon();
    out.println("连接成功...");
 } catch (Exception e) {   
     e.printStackTrace();   
 }
 %>   
   </body>   
 </html> 
 
 在浏览器输入地址,可以看到运行结果
 
 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值