/** * 从apache提供的连接池中取连接,失败返回false * * @return boolean * @date: */ private boolean getApachecommonDBCP() { try { Context tContext = new InitialContext(); tContext = (Context) tContext.lookup("java:comp/env"); Object obj = tContext.lookup(JUrl.getDBName()); DataSource tDataSource = (DataSource) obj; if (tDataSource != null) { con = tDataSource.getConnection(); // 如果连接的是Oracle数据库,需要稍微处理一下日期的格式,最好是在服务器哪里设置一下,而不调用下面的程序 // 可以添加一个字段类型,来控制是否使用下面的语句 if (con != null) { // Statement stmt = con.createStatement(ResultSet. // TYPE_SCROLL_SENSITIVE, // ResultSet.CONCUR_UPDATABLE); // stmt.execute( // "alter session set nls_date_format = 'YYYY-MM-DD // HH24:MI:SS'"); // stmt.close(); return true; } return false; } else { System.out.println("a error occured when geting datasource"); return false; } } catch (Throwable e) { System.out.println("failure when connect apache commons dbcp "); e.printStackTrace(); return false; } }
/** * 从WebSphere提供的连接池中取连接,失败返回false * * @return boolean */ private boolean getWebSpherePoolConnection() { try { Context tContext = new InitialContext(); // 如果在web.xml中声明了引用对象,则采用下面的方法 DataSource tDataSource = (DataSource) tContext.lookup(JUrl.getDBName()); // 下面的方法也可以发现到jndi数据 // DataSource tDataSource = (DataSource) tContext.lookup("jdbc/MET"); // 不过会在日志中输出如下错误信息,websphere不建议采用 // [03-9-2 17:19:11:916 CST] 6b0e97e8 ConnectionFac I J2CA0122I: 无法定位资源引用 // jdbc/db2ds,因此使用下列缺省值:[Resource-ref settings] // res-auth: 1 (APPLICATION) // res-isolation-level: 0 (TRANSACTION_NONE) // res-sharing-scope: true (SHAREABLE) // res-resolution-control: 999 (undefined) if (tDataSource != null) { con = tDataSource.getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // stmt.execute("alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'"); stmt.close(); if (con != null) { System.out.println("Connect succeed from websphere!"); return true; } else { System.out.println("new Connection error ..."); return false; } } else { System.out.println("new DataSource error ..."); return false; } } catch (Throwable e) { System.out.println("look for jndi name error ..."); e.printStackTrace(); return false; } }