/*
* Created on 2005-1-26
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import java.sql.*;
import javax.sql.*;//数据元
import javax.naming.*;//JNDI
public class ConnectionLocator {
private String errMessage; //错误信息
private DataSource crocodileDS; //数据源
static private ConnectionLocator connectionLocator=new ConnectionLocator() ; //创建对象
private ConnectionLocator()//构造函数
{
}
static public ConnectionLocator getInstance()//得到对象
{
return connectionLocator;
}
public Connection getConnection(String param) //得到连接
{
Context ctx=null;
Connection con=null;
try
{
ctx=new InitialContext(); //创建上下文环境
crocodileDS=(DataSource)ctx.lookup(param); //查找数据源
con=crocodileDS.getConnection();
}catch(NamingException e1)
{
System.out.println(e1.getMessage());
errMessage="数据库驱动不存在!";
return null;
}
catch(SQLException e2)
{
errMessage="数据库异常!";
return null;
}
return con;
}
/*说明:构建一个JDBC连接,param是数据源的JNDI名。函数中如果捕获异常,则返回的Connection值为null,并在成员变量errMessage中保存错误消息*/
// 使用该变量保存方法getConnection中使用JNDI名lookup的结果,减少查找的时间消耗
public String getMessage()
{
return errMessage;
}
/*说明:返回errMessage*/
}