Java Blog for Alex Wan

Let life be beautiful like summer flowers and death like autumn leaves.

统计

留言簿(10)

BlogJava

Blogs

DIV+CSS

JQuery相关

友情链接

常去的地方

数据供应

阅读排行榜

评论排行榜

tomcat数据源读取的简单例子

应朋友的要求写下这篇文章,实现一个简单的例子,用于读取tomcat数据源

BaseDAO.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class BaseDAO
{
 
private static DataSource pool = null;
 
private static Context env = null;
 
//private Connection conn = null;
 protected String tableName="";
 
public BaseDAO() throws AppException//构造
 {
  
if (pool != nullreturn;
  
  
try
  
{
   env 
= (Context) new InitialContext().lookup("java:comp/env");
   pool 
= (DataSource)env.lookup("jdbc/" + "appid");//数据源id
  }

  
catch(NamingException ne) 
  
{
   env 
= null;
   pool 
= null;
   System.out.println(ne.getMessage());
   
throw new AppException(ne.getMessage());
  }

 }

 
 
public Connection getConn() throws AppException//获取连接
 {
  
try
  
{
   
if (pool == null)
    
throw new AppException("Data source invalid!");
   
else
    
return pool.getConnection();
  }

  
catch(SQLException e) 
  
{
   
throw new AppException(e.getMessage());
  }

 }

 
 
public void closeConn(Connection conn)//关闭连接
 {
  
try
  
{
   
if (conn != null) conn.close();
  }

  
catch (Exception e)
  
{
  }

 }

}

另外AppException的实现如下:
AppException.java

import java.lang.Exception;

public class AppException extends Exception
{
 
/**
  * 
  
*/

 
private static final long serialVersionUID = 1L;

 
public AppException(Exception exc)
 
{
  
super(exc.getCause());
 }

 
 
public AppException(String errorMessage)
 
{
  
super(errorMessage);
 }

}


 

其实这一种方式也不是最好的方式,而且依赖tomcat的数据源,开启了连接后一定要记得关闭连接,这样管理起来容易出错,建议可以是使用ibatis替代



Let life be beautiful like summer flowers and death like autumn leaves.

posted on 2008-06-07 10:21 Alexwan 阅读(1029) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: