设置数据库连接池的两种方法

http://c20000001.blog.163.com/blog/static/115475412008103054214782/
driverClassName = "com.mysql.jdbc.Driver"    
或者
org.gjt.mm.mysql.Driver

设置数据库连接池的两种方法

这几天在弄个小东西,要用到数据库,以前就听说过数据库连接池这个概念,所以就打算在这个小东西中加入数据库连接池。呵呵。从网上搜了一些资料。今天就整理一下。我搜到的设置基本上主要有两种方法我们以MySQL+TOMCAT为例 
1.
DataSource设置到我们的WEB项目中,下面详细的介绍下:
 
第一步:在我们的WEB项目中的META-INF文件夹下建立一个context.xml

Xml代码

  1. <?xml version='1.0' encoding='utf-8'?>  
  2.   
  3. <Context>  
  4.   
  5.     <Resource name="jdbc/mysql"      
  6.        auth="Container"      
  7.        type="javax.sql.DataSource"      
  8.        driverClassName="com.mysql.jdbc.Driver"      
  9.        url="jdbc:mysql://localhost/bbs"      
  10.        username="root"      
  11.        password="root"      
  12.        maxActive="50"      
  13.        maxIdle="20"      
  14.        maxWait="10000" />      
  15.   
  16. </Context>  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


第二步:在我们的WEB项目下的WEB-INF文件夹下建立一个web.xml(如果存在了就不用了,直接修改就行了
(
这几天测试了一下,不做这步也可以,O(∩_∩)O哈哈~省事了)

Xml代码

  1. <resource-ref>  
  2.     <description>DB Connection</description>  
  3.     <res-ref-name>jdbc/mysql</res-ref-name>  
  4.     <res-type>javax.sql.DataSource</res-type>  
  5.     <res-auth>Container</res-auth>  
  6. </resource-ref>  

 

 

 

 

 

 


第三步:我们就可以用代码来获取Connection对象了

Java代码

  1. package xushun.util;   
  2.   
  3. import java.sql.*;   
  4. import javax.sql.*;   
  5. import javax.naming.*;   
  6.   
  7. public class DBHelper {   
  8.        
  9.     public static Connection getConnection() throws SQLException,NamingException   
  10.     {   
  11.         // 初始化查找命名空间   
  12.         Context initContext new InitialContext();   
  13.         Context envContext (Context)initContext.lookup("java:/comp/env");   
  14.         // 找到DataSource   
  15.         DataSource ds (DataSource)envContext.lookup("jdbc/mysql");   
  16.         return ds.getConnection();   
  17.     }   
  18.  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


2.
DataSource设置到我们的Tomcat中,下面详细的介绍下(测试用的JAVA代码和上面的一样就不帖出了): 
这里我查到的设置方法就有了一点区别了。有的人把DataSource设置在Tomcatserver.xml文件的GlobalNamingResources下面,然后在context.xml中去映射。有的直接就写在context.xml中了 
先说下在server.xml添加DataSource
 
第一步:在Tomcatconf中的server.xml文件中找到

Xml代码

  1. <GlobalNamingResources>  
  2.   <!-- Editable user database that can also be used by   
  3.        UserDatabaseRealm to authenticate users   
  4.   -->  
  5.   <Resource name="UserDatabase" auth="Container"  
  6.             type="org.apache.catalina.UserDatabase"  
  7.             description="User database that can be updated and saved"  
  8.             factory="org.apache.catalina.users.MemoryUserDatabaseFactory"  
  9.             pathname="conf/tomcat-users.xml" />  
  10. </GlobalNamingResources>  

 

 

 

 

 

 

 

 

 

 

修改为

Xml代码

  1. <GlobalNamingResources>  
  2.   <!-- Editable user database that can also be used by   
  3.        UserDatabaseRealm to authenticate users   
  4.   -->  
  5.   <Resource name="UserDatabase" auth="Container"  
  6.             type="org.apache.catalina.UserDatabase"  
  7.             description="User database that can be updated and saved"  
  8.             factory="org.apache.catalina.users.MemoryUserDatabaseFactory"  
  9.             pathname="conf/tomcat-users.xml" />  
  10.   <Resource name="jdbc/bbs"        
  11.          auth="Container" type="javax.sql.DataSource"  
  12.          driverClassName="com.mysql.jdbc.Driver"  
  13.          maxIdle="20"  
  14.          maxWait="5000"  
  15.          username="root"  
  16.          password="admin"  
  17.          url="jdbc:mysql://localhost:3306/bbs"        
  18.          maxActive="100"    
  19.          removeAbandoned="true"  
  20.          removeAbandonedTimeout="60"  
  21.          logAbandoned="true"/>  
  22. </GlobalNamingResources>  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


第二步:在Tomcatconf文件夹下的context.xml中加入

Xml代码

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

 


第三步:就是在WEB项目的WEB-INF中的web.xml添加

Xml代码

  1. <resource-ref>  
  2.     <description>DB Connection</description>  
  3.     <res-ref-name>jdbc/mysql</res-ref-name>  
  4.     <res-type>javax.sql.DataSource</res-type>  
  5.     <res-auth>Container</res-auth>  
  6. </resource-ref>  

 

 

 

 

 

 


还有就是在Tomcat文档中提到的方法,直接修改context.xml文件了 
Tomcatconf文件夹下的context.xml中加入

Xml代码

  1. <Resource name="jdbc/bbs"        
  2.               auth="Container" type="javax.sql.DataSource"  
  3.               driverClassName="com.mysql.jdbc.Driver"  
  4.               maxIdle="20"  
  5.               maxWait="5000"  
  6.               username="root"  
  7.               password="admin"  
  8.               url="jdbc:mysql://localhost:3306/bbs"        
  9.               maxActive="100"    
  10.               removeAbandoned="true"  
  11.               removeAbandonedTimeout="60"  
  12.               logAbandoned="true"/>  

 

 

 

 

 

 

 

 

 

 

 

 

然后就是在WEB项目的WEB-INF中的web.xml添加

Xml代码

  1. <resource-ref>  
  2.     <description>DB Connection</description>  
  3.     <res-ref-name>jdbc/mysql</res-ref-name>  
  4.     <res-type>javax.sql.DataSource</res-type>  
  5.     <res-auth>Container</res-auth>  
  6. </resource-ref>  

 

 

 

 

 

 


就是这些了,如果有什么不太清楚的就留言,一起研究下。等以后我在搜集下资料整理出上面用到的XML文件中各个标签的属性及其代表的意思。有兴趣的也可以自己先查下。:-) 

<td>JNDI 
查找名称</td>       <td>关联的引用</td> 

<td>java:comp/env</td>      <td>
应用程序环境条目
</td> 

<td>java:comp/env/jdbc</td> <td>JDBC 
数据源资源管理器连接工厂
</td> 

<td>java:comp/env/ejb</td>  <td>EJB 
引用
</td> 

<td>java:comp/UserTransaction</td><td>UserTransaction 
引用
</td> 

<td>java:comp/env/mail</td> <td>JavaMail 
会话连接工厂
</td> 

<td>java:comp/env/url</td>  <td>URL 
连接工厂
</td> 

<td>java:comp/env/jms</td>  <td>JMS 
连接工厂和目标
</td> 

<td>java:comp/ORB</td>      <td>
应用程序组件之间共享的 ORB 实例</td>

<think>我们正在讨论蛋糕商城项目中使用c3p0数据库连接池两种方法。根据引用[1]和[2],c3p0是一个实现了javax.sql.DataSource接口的连接池工具集,它管理数据库连接,减少创建和关闭连接的开销。在Java中,通常有两种配置c3p0的方法:通过配置文件(c3p0-config.xml)和通过编程方式直接设置参数。方法一:使用配置文件(c3p0-config.xml)这是最常用的方式。在项目的类路径(如src目录或resources目录)下创建c3p0-config.xml文件,配置连接池参数。然后在代码中通过`ComboPooledDataSource`类获取数据源。示例配置文件(c3p0-config.xml):```xml<c3p0-config><!--默认配置--><default-config><propertyname="driverClass">com.mysql.jdbc.Driver</property><propertyname="jdbcUrl">jdbc:mysql://localhost:3306/cake_db</property><propertyname="user">root</property><propertyname="password">123456</property><!--连接池参数--><propertyname="initialPoolSize">5</property><propertyname="maxPoolSize">20</property><propertyname="minPoolSize">5</property><propertyname="acquireIncrement">5</property></default-config></c3p0-config>```在Java代码中,我们可以这样使用:```javaimportcom.mchange.v2.c3p0.ComboPooledDataSource;importjavax.sql.DataSource;importjava.sql.Connection;importjava.sql.SQLException;publicclassC3P0Utils{//使用默认配置(即上面配置文件中default-config)privatestaticComboPooledDataSourcedataSource=newComboPooledDataSource();publicstaticDataSourcegetDataSource(){returndataSource;}publicstaticConnectiongetConnection()throwsSQLException{returndataSource.getConnection();}}```方法二:编程方式配置如果不使用配置文件,我们也可以在代码中直接设置连接池的参数。示例代码:```javaimportcom.mchange.v2.c3p0.ComboPooledDataSource;importjavax.sql.DataSource;importjava.beans.PropertyVetoException;importjava.sql.Connection;importjava.sql.SQLException;publicclassC3P0Utils{privatestaticComboPooledDataSourcedataSource;static{try{dataSource=newComboPooledDataSource();dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/cake_db");dataSource.setUser("root");dataSource.setPassword("123456");//设置连接池参数dataSource.setInitialPoolSize(5);dataSource.setMaxPoolSize(20);dataSource.setMinPoolSize(5);dataSource.setAcquireIncrement(5);}catch(PropertyVetoExceptione){e.printStackTrace();}}publicstaticDataSourcegetDataSource(){returndataSource;}publicstaticConnectiongetConnection()throwsSQLException{returndataSource.getConnection();}}```在蛋糕商城项目中,推荐使用配置文件的方式,因为这样可以在不修改代码的情况下调整连接池参数,便于维护。引用[3]提到,c3p0通过预先创建一定数量的连接并重复利用,减少了连接的创建和关闭开销,提高了性能。因此,在项目中正确配置和使用c3p0连接池非常重要。注意:在代码中获取连接后,使用完毕应调用`close()`方法将连接归还给连接池,而不是真正关闭连接。如引用[1]中的示例代码所示,调用`close()`后,连接会被归还,后续可以再次获取。在蛋糕商城项目中,我们可以将上述工具类(如C3P0Utils)放在一个公共包中,然后在需要数据库连接的地方调用`C3P0Utils.getConnection()`来获取连接。§§相关问题§§1.在蛋糕商城项目中,如何确保c3p0配置文件被正确加载?2.如果数据库连接池中的连接被耗尽,可能是什么原因?如何解决?3.除了c3p0,蛋糕商城项目还可以使用哪些数据库连接池?</think>### c3p0数据库连接池在蛋糕商城项目中的两种实现方法 在蛋糕商城项目中,c3p0数据库连接池可通过以下两种方式实现: #### 方法1:配置文件方式(推荐) **实现步骤**: 1. 创建`c3p0-config.xml`配置文件(放在`src`目录下): ```xml <c3p0-config> <named-config name="cakeDB"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/cake_shop</property> <property name="user">root</property> <property name="password">123456</property> <!-- 连接池参数 --> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> <property name="minPoolSize">5</property> <property name="acquireIncrement">3</property> </named-config> </c3p0-config> ``` 2. 创建工具类`C3P0Utils.java`: ```java import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Utils { private static final ComboPooledDataSource ds = new ComboPooledDataSource("cakeDB"); // 匹配配置名称 public static Connection getConnection() throws SQLException { return ds.getConnection(); } } ``` 3. 在DAO层调用: ```java public class CakeDAO { public List<Cake> getAllCakes() { try (Connection conn = C3P0Utils.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM cakes")) { // 执行查询操作... } } } ``` #### 方法2:编程式配置方式 **实现步骤**: ```java import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Manager { private static ComboPooledDataSource ds; static { try { ds = new ComboPooledDataSource(); ds.setDriverClass("com.mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc:mysql://localhost:3306/cake_shop"); ds.setUser("root"); ds.setPassword("123456"); // 配置连接池参数 ds.setInitialPoolSize(5); ds.setMinPoolSize(5); ds.setMaxPoolSize(20); ds.setAcquireIncrement(3); } catch (PropertyVetoException e) { throw new RuntimeException("C3P0 config error", e); } } public static Connection getConnection() throws SQLException { return ds.getConnection(); } } ``` ### 两种方法的对比 | **特性** | 配置文件方式 | 编程式配置方式 | |----------------|--------------------------------|---------------------------| | **维护性** | 修改配置无需重新编译代码 | 需修改代码并重新编译 | | **灵活性** | 支持多环境配置(开发/生产) | 配置硬编码在代码中 | | **热更新** | 支持配置文件热加载 | 需重启应用 | | **推荐场景** | 生产环境首选 | 快速原型开发/简单项目 | ### 关键注意事项 1. **连接释放**:必须调用`Connection.close()`将连接归还连接池[^1] 2. **参数调优**: - `maxPoolSize`应根据商城并发量设置 - `acquireIncrement`影响连接增长步长 3. **异常处理**:建议使用`try-with-resources`确保连接关闭 4. **连接泄漏防护**:启用`unreturnedConnectionTimeout`检测未关闭连接 > 在蛋糕商城这类电商项目中,推荐使用**配置文件方式**,便于运维人员根据实际负载动态调整连接池参数。c3p0通过重用连接显著降低数据库开销[^3],在高并发场景下单商品页查询性能可提升$3-5$倍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zlingh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值