使用JNDI連接數據庫

第一步:實現一個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>  

 

在瀏覽器輸入地址,可以看到運行結果:

使用JNDI連接數據庫 <wbr>(DataSource)ctx.lookup("java:comp/env/jdbc/DBPool")

OK,連接成功!


轉載:http://blog.sina.com.cn/s/blog_613963d10100stor.html

發佈了13 篇原創文章 · 獲贊 19 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章