应朋友的要求写下这篇文章,实现一个简单的例子,用于读取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 != null) return;
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替代