javaweb基础----c3p0数据库连接池的相关配置

1.导入jar包

c3p0-0.9.1.2.jar

2.在项目的根路径src下创建一个xml文件,命名为c3p0-config.xml(必须此名

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <c3p0-config>
 3     <!-- 默认配置,如果没有指定则使用这个配置 -->
 4     <default-config>
 5         <property name="driverClass">com.mysql.jdbc.Driver</property>
 6         <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/estore?useSSL=false</property>
 7         <property name="user">vincent</property>
 8         <property name="password">vincent</property>
 9     </default-config>
10     
11     <!-- 自定义配置 -->
12     <named-config name="myDataSource">
13         <property name="driverClass">com.mysql.jdbc.Driver</property>
14         <property name="jdbcUrl">jdbc:mysql://localhost:3306/estore?useSSL=false</property>
15         <property name="user">vincent</property>
16         <property name="password">vincent</property>
17         
18         <!-- 初始化时创建的连接数  default:3-->
19         <property name="initialPoolSize">3</property>
20         <!-- 连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接,如果为0,则永远不会断开连接,default:0  单位:秒 -->
21         <property name="maxIdleTime">0</property>
22         <!-- 连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待其他连接释放,所以这个值有可能会设计地很大 default:15 -->
23         <property name="maxPoolSize">15</property>
24         <!-- 连接池保持的最小连接数 default:3-->
25         <property name="minPoolSize">3</property>
26         <!-- 连接池在无空闲连接可用时一次性创建的新数据库连接数  default:3-->
27         <property name="acquireIncrement">3</property>
28     </named-config>
29 </c3p0-config> 

3.编写连接工具类

 1 public class DBUtils {
 2     private static final ComboPooledDataSource DATA_SOURCE = new ComboPooledDataSource();
 3     //为保证取得的是同一连接,使用ThreadLocal保证同一线程数据共享
 4     public static final ThreadLocal<Connection> TL = new ThreadLocal<>();
 5     // 获取数据源
 6     public static DataSource getDataSource() {
 7         return DATA_SOURCE;
 8     }
 9 
10     // 获取连接
11     public static Connection getConnection() throws SQLException {
12         Connection conn = null;
13         //第一次,尝试从ThreadLocal中获取连接
14         conn = TL.get();
15         //如果没有取到,从连接池中随机获取一个连接
16         if(conn==null) {
17             conn =DATA_SOURCE.getConnection();
18             //将连接放到线程中
19             TL.set(conn);
20         }
21          return conn;
22     }
23 }
先想再做,不想不做。
原文地址:https://www.cnblogs.com/cjasonvincent/p/8685699.html