Tomcat中通过JNDI配置访问数据库

1,所需要的jar文件:commons-pool.jar, commons-dbcp.jar

2,server.xml的配置:

<Resource name="jdbc/hellohibernate" scope="Shareable" auth="Container"
 type="javax.sql.DataSource"/>
  <ResourceParams name="jdbc/hellohibernate">
   <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
   </parameter>
   <parameter>
              <name>removeAbandoned</name>
              <value>true</value>
            </parameter>
   <parameter>
              <name>logAbandoned</name>
              <value>true</value>
            </parameter>
   <!-- DBCP database connection settings -->
   <parameter>
    <name>url</name>
    <value>jdbc:mysql://localhost:3306/test</value>
   </parameter>
   <parameter>
    <name>driverClassName</name><!--<value>com.mysql.jdbc.Driver</value>-->
    <value>org.gjt.mm.mysql.Driver</value>
   </parameter>
   <parameter>
    <name>username</name>
    <value>root</value>
   </parameter>
   <parameter>
    <name>password</name>
    <value></value>
   </parameter>

   <!-- DBCP connection pooling options -->
   <parameter>
    <name>maxWait</name>
    <value>3000</value>
   </parameter>
   <parameter>
    <name>maxIdle</name>
    <value>100</value>
   </parameter>
   <parameter>
    <name>maxActive</name>
    <value>10</value>
   </parameter>
  </ResourceParams>

3,程序中的调用:

Context ctx = new InitialContext();
            if (ctx == null)
                throw new Exception("Boom - No Context");

            DataSource ds =
                (DataSource) ctx.lookup(
                "java:comp/env/jdbc/hellohibernate");

            if (ds != null) {
                Connection conn = ds.getConnection();

                if (conn != null) {
                    foo = "Got Connection " + conn.toString();
                    Statement stmt = conn.createStatement();
                    ResultSet rst =
                        stmt.executeQuery(
                        "select username,id from user");
                    if (rst.next()) {
                        foo = rst.getString(1);
                        bar = rst.getInt(2);
                    }
                    conn.close();
                }
            }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值