tomcat环境使用jndi连接oracle数据库

1.在项目WEB-INF/web.xml中增加如下代码:

<resource-ref>
        <description>Admin connect to DB</description>
        <res-ref-name>jndiconn</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

res-ref-name很重要,与context.xml中的name要一致。

2.tomcat的context.xml中增加配置如下:

<Resource name="jndiconn" auth="Container" type="javax.sql.DataSource"
        maxActive="100" minIdle="10" maxWait="10000" initialSize="10"
        username="test" password="test" driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@127.0.0.1:1521:orcl" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        testWhileIdle="true" testOnBorrow="true" testOnReturn="false"
        validationQuery="SELECT 1 from dual" validationInterval="30000"
        timeBetweenEvictionRunsMillis="30000" removeAbandonedTimeout="60"
        removeAbandoned="true" logAbandoned="true" minEvictableIdleTimeMillis="30000"
        jmxEnabled="true"
        jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" />

3.将oracle驱动程序加入到tomcat的lib中

D:\apache-tomcat-7.0.57-windows-x64\apache-tomcat-7.0.57\lib

4.java连接数据源代码:

    public static Connection getConnection() {
        Connection conn = null;
        try {
            // jdbc
            // InputStream inputStream = CommonUtils.class
            // .getResourceAsStream("databaseConfig.properties");
            // Properties p = new Properties();
            // p.load(inputStream);
            // String driver = p.getProperty("driverName");
            // String url = p.getProperty("databaseUrl");
            // String userName = p.getProperty("userName");
            // String passWord = p.getProperty("passWord");
            // Class.forName(driver);
            // conn = DriverManager.getConnection(url,userName,passWord);
            // conn.setAutoCommit(false);

            // jndi
            Context initContext = new InitialContext();
            DataSource dataSource = (DataSource) initContext
                    .lookup("java:comp/env/jndiconn");
            return dataSource.getConnection();
        } catch (Exception e) {
            System.out.println("建立数据库连接错误!" + e.toString());
            e.printStackTrace();
        }
        return conn;
    }


5.完成jndi连接oracle数据库。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值