tomcat7中配置c3p0数据库连接池。
是在eclipse for j2ee中开发的。
参考的是:http://bioubiou.iteye.com/blog/1776589和http://bbs.csdn.net/topics/390708897
注意:下面配置出来的好像是全局连接池,不是局部连接池。
注意:我开发使用的是eclipse for j2ee。
好像eclipse中启动tomcat时使用的配置好像是eclipse工程中的Servers中的配置,所以我们需要配置的是eclipse工程中的Servers,而不是去配置安装了的tomcat。
步骤如下:
1、将下面的内容写入到Servers下的Tomcat v7.0 Server at localhost-config目录下的server.xml的GlobalNamingResources中,之后保存
<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" />
2、打开Servers下的Tomcat v7.0 Server at localhost-config目录下的context.xml,将下面的内容添加到Context中,之后保存。
<ResourceLink name="jdbc/connPool"
global="jdbc/connPool" type="javax.sql.DataSource"/>
3、将下面的内容添加到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>
4、将c3p0-0.9.1.jar和mysql-connector-java-5.1.24-bin.jar添加到安装了的tomcat的安装目录的lib下,如下图所示:
5、将mysql-connector-java-5.1.24-bin.jar放置在web工程的web/lib下。
6、现在可以在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;
}
}
7、取得连接之后就可以进行操作数据库了。