第一步:实现一个Java类:

package com.logistic.data;

import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.sql.Date;
//import java.text.SimpleDateFormat;

public class DataConnect {
 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.print(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");
    //tempstr=str.replace('\'',(char)1);
    
    
   }catch(Exception e){
    System.out.println("inStr");
    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()就可以获取到连接了,其他是多余的

接下来是重点,也就是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>

在浏览器输入地址,可以看到运行结果:

OK,连接成功!

使用JNDI连接数据库的更多相关文章

  1. tomcat6配置jndi连接数据库的方式

    eworkflow工作流+eform表单+ebiao报表集成在一起,用tomcat6发布,并用jndi连接数据库,数据库是sqlserver2005,配置如下: 1.在tomcat6\conf\con ...

  2. 用JNDI连接数据库

    之前说到了利用Java中的Properties类读取properties配置文件,连接数据库,现在说另一种方法,他们的目的和作用都是一样的,都是为了提高代码的复用性,解决了更改数据库 时还要更改代码的 ...

  3. JNDI连接数据库的详细步骤 以及简要的c3po数据库连接的配置

    第一步在tomcat的context.xml文件中配置数据源:context.xml的路径形式是:D:\Program Files (x86)\apache-tomcat-6.0.44\conf\co ...

  4. Tomcat,Jboss,Weblogic通过jndi连接数据库

    1.  Tomcat配置Jndi数据源 1.1在tomcat服务器的lib目录下加入数据库连接的驱动jar包 1.2修改tomcat服务器的conf目录下server.xml配置文件 编辑server ...

  5. jndi连接数据库配置过程总结

    一.我们先找到tomcat安装目录中conf目录下的context.xml更改里面的内容: <?xml version='1.0' encoding='utf-8'?> <Conte ...

  6. Quartz集群配置

    先看看quartz的持久化基本介绍: 引用 1 大家都清楚quartz最基本的概念就是job,在job内调用具体service完成具体功能,quartz需要把每个job存储起来,方便调度,quartz ...

  7. javax.naming.NoInitialContextException错误的解决方案

    今天,学习用了一下nutz框架,写了一个HelloWorld的小程序,在用jndi配置数据源时,写了一个测试类,并在main方法中调用了jndi获得数据库连接,但是报错了,错误信息如下: javax. ...

  8. javax.naming.NoInitialContextException: Need to specify class name in environment or system property

    javax.naming.NoInitialContextException: Need to specify class name in environment or system property ...

  9. Tomcat 配置连接池

    1. Tomcat 配置 JNDI 资源 JNDI(Java Naming and Directory Interface), Java 命名和目录接口; JNDI 作用: 在服务器上配置资源, 然后 ...

随机推荐

  1. 五、python的练习题

    1.输入一行字符,分别统计出其中英文字母.空格.数字和其他字符的个数. #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/5 ...

  2. python开发_random

    和java中的random()函数一样,在python中也有类似的模块random,即随机数 下面是我做的demo 运行效果: ==================================== ...

  3. YII 关联查询

    通过外键自己关联自己

  4. 使用Win2D在UWP程序中2D绘图(二)

    绘制API 首先还是看一下前文的的示例: args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.Black, 3);    args.Dra ...

  5. BOOST Converter Analog/Digital Adjusted Output Voltage TPS61045 MAX1932

    DIGITALLY ADJUSTABLE BOOST CONVERTER The TPS61045 is a high frequency boost converter with digitally ...

  6. Spring使用@Required注解依赖检查

    Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种情况,你需要 @Required ...

  7. spring-cloud服务器雪崩效应

    在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用.为了保证其高可用,单个服务 ...

  8. Junit初级篇

    @Test介绍 @Test是我们在写测试脚本时最常用到的,大部分情况下如果没用这个注解,一个方法就不能成为测试用例.如下代码是一个最普通的测试脚本: import org.junit.Assert; ...

  9. Java中23种经典设计模式详解

    Java中23种设计模式目录1. 设计模式 31.1 创建型模式 41.1.1 工厂方法 41.1.2 抽象工厂 61.1.3 建造者模式 101.1.4 单态模式 131.1.5 原型模式 151. ...

  10. MySQL Cluster(MySQL 集群) 初试

    MySQL Cluster 是MySQL适合于分布式计算环境的高实用.高冗余版本.它采用了NDB Cluster 存储引擎,允许在1个 Cluster 中运行多个MySQL服务器.在MyQL 5.0及 ...