mysql jdbc 连接池配置

数据库使用:MySQL 5.5.55

web服务器使用:tomcat 7

文档:

mysql jdbc connect 链接文档:点击打开链接

连接池在Tomcat配置文档:点击打开链接

连接池使用文档:点击打开链接

问题:

由于web服务器版本问题,无法完全按照官方文档给出说明配置,有以下问题:

在web服务器中,server.xml 文件中缺少上下文结构(),在本版本中,我的web服务器上下文结构在context.xml中

粘贴文档中:

配置上下文xml

 

  ...

  

  
    
      factory
      org.apache.commons.dbcp.BasicDataSourceFactory
    

    
      maxActive
      10
    

    
      maxIdle
      5
    

    
      validationQuery
      SELECT 1
    

    
      testOnBorrow
      true
    

    
      testWhileIdle
      true
    

    
      timeBetweenEvictionRunsMillis
      10000
    

    
      minEvictableIdleTimeMillis
      60000
    

    
     username
     someuser
    

    
     password
     somepass
    

    
       driverClassName
       com.mysql.jdbc.Driver
    

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

  
在我的web服务器中报错无法匹配 resourceparams

后改成


成功配置。

在java中新建DBconnection类

public class DBconnect {
	public static  Connection getConnection() throws SQLException{
		 /*
	     * Create a JNDI Initial context to be able to
	     *  lookup  the DataSource
	     *
	     * In production-level code, this should be cached as
	     * an instance or static variable, as it can
	     * be quite expensive to create a JNDI context.
	     *
	     * Note: This code only works when you are using servlets
	     * or EJBs in a J2EE application server. If you are
	     * using connection pooling in standalone Java code, you
	     * will have to create/configure datasources using whatever
	     * mechanisms your particular connection pooling library
	     * provides.
	     */

	    InitialContext ctx=null;
		try {
			ctx = new InitialContext();
		} catch (NamingException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

	     /*
	      * Lookup the DataSource, which will be backed by a pool
	      * that the application server provides. DataSource instances
	      * are also a good candidate for caching as an instance
	      * variable, as JNDI lookups can be expensive as well.
	      */

	    DataSource ds = null;
		try {
			ds = (DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
		} catch (NamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    /*
	     * The following code is what would actually be in your
	     * Servlet, JSP or EJB 'service' method...where you need
	     * to work with a JDBC connection.
	     */

	      return ds.getConnection();
	}

}

需要注意的是:在类中获取数据源方法:

			ds = (DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
此处 格式应为java:comp/env/+(ResourceParams中的name)

至此,配置成功。


你可能感兴趣的:(java,web)