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

null | 阅2968 来源:好空间网络 [打印] [关闭]
 

1,所需要的jar文件:commons-pool.jar, commons-dbcp.jar
  
  2,server.xml的配置:
     type="javax.sql.DataSource"/>
   
   
    factory
    org.apache.commons.dbcp.BasicDataSourceFactory
   

   
         removeAbandoned
         true
        

   
         logAbandoned
         true
        

   
   
    url
    jdbc:mysql://localhost:3306/test
   

   
    driverClassName
    org.gjt.mm.mysql.Driver
   

   
    username
    root
   

   
    password
    
   

  
   
   
    maxWait
    3000
   

   
    maxIdle
    100
   

   
    maxActive
    10
   

   

  
  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();
          }
        }
  

经营许可证ICP:皖B2-20100052 公司邮箱:zcdnsz@jspkongjian.net
Copyright © 2004-2015, 安徽好空间网络科技有限公司 版权所有 , 本站素材部分来源于网络,如有侵权请告知删除。