JNDI(Java Naming and Directory Interface) 方法一: 获得容器(Tomcat)的Connection对象 环境 Tomcat + Oracle g; 步骤将Oracle驱动拷贝到Tomcat容器lib目录下; 写配置文件; 编辑容器conf目录下contextxml文件在节点中新增一个节点 <Resource name=sos/sosDB auth=Container type=javaxsqlDataSource driverClassName=oraclejdbcdriverOracleDriver url=jdbc:oracle:thin:@::sos username=oa password=oa maxActive= maxIdle= maxWait=/> <Resource name=sos/sosDB auth=Container type=javaxsqlDataSource driverClassName=oraclejdbcdriverOracleDriver url=jdbc:oracle:thin:@::sos username=oa password=oa maxActive= maxIdle= maxWait=/> 其中driverClassName为oracle驱动名称url为数据库的链接地址username为数据库用户 名password数据库的密码 编写获得容器提供的Connection对象的代码; import javasqlConnection; import javaxnamingContext; import javaxnamingInitialContext; import javaxsqlDataSource; public class JdbcUtil { /* * 进行数据库的连接操作 */ public static Connection getConnection() { Connection conn = null; try { Context ctx = new InitialContext(); DataSource ds = (DataSource)ctxlookup(java:/comp/env/sos/sosDB); conn = dsgetConnection(); }catch(Exception e) { eprintStackTrace(); } return conn; } } import javasqlConnection; import javaxnamingContext; import javaxnamingInitialContext; import javaxsqlDataSource; public class JdbcUtil { /* * 进行数据库的连接操作 */ public static Connection getConnection() { Connection conn = null; try { Context ctx = new InitialContext(); DataSource ds = (DataSource)ctxlookup(java:/comp/env/sos/sosDB); conn = dsgetConnection(); }catch(Exception e) { eprintStackTrace(); } return conn; } } 注: java:/comp/env/sos/sosDB中/sos/sosDB必须和配置文件节点中name的值相同 |