请教一个有关怎么得到数据源的问题?

ljc1977 2003-08-19 02:47:07
环境:jboss3.2.1数据源已经配置好了,servlet可以得到数据源,请问,用一个class能不能得到服务器的数据源,可否使用InitialContext init = new InitialContext(); Datasource ds = init.lookup("jndiname");
ds.getConnection();得到连接
...全文
70 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
frankspy 2004-02-29
  • 打赏
  • 举报
回复
up~`
xiayuliang 2003-08-29
  • 打赏
  • 举报
回复
给你一个例子吧:

public class ConnBean {

protected static String source = "jdbc/ORACLEDB";

protected static String strErrMsg = "";

/**
* DBConnection 构造子注解。
*/
public ConnBean() {
super();
}

/**
* 取数据库连接
* 创建日期:(2002-4-28 11:33:25)
*/
public static Connection getConnection() {
java.sql.Connection con = null;
DataSource ds = null;

//取系统数据源
try {
//创建JNDI命名上下文
Context initCtx = new InitialContext();
//使用 java:comp/env 环境命名上下文(environment naming context(ENC))
Context envCtx = (Context) initCtx.lookup("java:comp/env");
//查找与JNDI命名source绑定的对象
ds = (DataSource) envCtx.lookup(source);


} catch (Exception e) {
e.printStackTrace();
strErrMsg = "DBConnection>>getConnection(取系统数据源出错):" + e.getMessage();
System.out.println("DBConnection>>getConnection(取系统数据源出错):" + e.getMessage());
writeLog(strErrMsg);
}

//焣数据库连接
if (!(ds == null)) {
try {
con = ds.getConnection();
} catch (Exception e) {
strErrMsg = "DBConnection>>getConnection(取数据库连接出错):" + e.getMessage();
System.out.println("DBConnection>>getConnection(取数据库连接出错):" + e.getMessage());
writeLog(strErrMsg);
}
}

//返回取得的数据库连接

return con;
}

/**
* 取返回错误信息。
* 创建日期:(2002-5-14 19:13:31)
*/
public static java.lang.String getStrErrMsg() {
return strErrMsg;
}
}

5,655

社区成员

发帖
与我相关
我的任务
社区描述
Web开发应用服务器相关讨论专区
社区管理员
  • 应用服务器社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧