tomcat7中配置c3p0数据库链接池

tomcat7中配置c3p0数据库链接池。 java

是在eclipse for j2ee中开发的。 mysql

参考的是:http://bioubiou.iteye.com/blog/1776589和http://bbs.csdn.net/topics/390708897 web

注意:下面配置出来的好像是全局链接池,不是局部链接池。 sql

注意:我开发使用的是eclipse for j2ee。 数据库

好像eclipse中启动tomcat时使用的配置好像是eclipse工程中的Servers中的配置,因此咱们须要配置的是eclipse工程中的Servers,而不是去配置安装了的tomcat。 apache

步骤以下: tomcat

一、将下面的内容写入到Servers下的Tomcat v7.0 Server at localhost-config目录下的server.xml的GlobalNamingResources中,以后保存 eclipse

    <Resource auth="Container" description="DB Connection" 
    driverClass="com.mysql.jdbc.Driver" 
    maxPoolSize="10" minPoolSize="2" acquireIncrement="2" 
    name="jdbc/connPool" user="帐号" password="密码" 
    factory="org.apache.naming.factory.BeanFactory" 
    type="com.mchange.v2.c3p0.ComboPooledDataSource" 
    jdbcUrl="jdbc:mysql://localhost:3306/数据库名?autoReconnect=true" />  ui

二、打开Servers下的Tomcat v7.0 Server at localhost-config目录下的context.xml,将下面的内容添加到Context中,以后保存。 spa

<ResourceLink name="jdbc/connPool" 
global="jdbc/connPool" type="javax.sql.DataSource"/> 

三、将下面的内容添加到web.xml中。

  <resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/connPool</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
  </resource-ref>
  
四、将c3p0-0.9.1.jar和mysql-connector-java-5.1.24-bin.jar添加到安装了的tomcat的安装目录的lib下,以下图所示:

五、将mysql-connector-java-5.1.24-bin.jar放置在web工程的web/lib下。

六、如今能够在java代码中取得Connection了,代码以下:

public class ConnectionUtil {

public static Connection getConnection(){
InitialContext initialContext = null;
Connection connection = null;
try {
initialContext = new InitialContext();
DataSource dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/connPool");
   connection = dataSource.getConnection();
   
} catch (NamingException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}

}

七、取得链接以后就能够进行操做数据库了。

相关文章
相关标签/搜索