多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 问题01:数据库连接池有什么作用? ![](https://img.kancloud.cn/f1/da/f1da3532e9e001f8c92eb7bc86fad8c6_803x439.png) ## 问题02:数据库连接池javax.sql.DataSource的重要API。 * JDBC提供了javax.sql.DataSource接口 * public static DataSource ds = null; **核心问题** * Connection javax.sql.DataSource.getConnection() ## 问题03:数据库连接池的手动实现。 * [ ] 使用线程安全的Vector容器存放Connection(C3P0使用的是LinkedList) ```   private Vector<Connection> freeConn = new Vector<Connection>();    private Vector<Connection> userConn = new Vector<Connection>();    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>(); ``` [https://www.likecs.com/show-203938020.html](https://www.likecs.com/show-203938020.html) ## 问题04:DBCP数据库连接池使用 ### 1. 导入jar包 ![](https://img.kancloud.cn/1c/d2/1cd2332071c82edcfeec797fcfe2770a_213x45.png) ### 2. 数据库信息配置 ![](https://img.kancloud.cn/19/5c/195c38d7bf1da801bcf2a071dc86278b_627x210.png) ### 3. 初始化数据源 1. 使用配置文件 ``` ds = BasicDataSourceFactory.createDataSource(prop); ``` 2. 手动配置 ``` public static DataSource ds = null; static { // 获取DBCP数据库连接池实现类对象 BasicDataSource bds = new BasicDataSource(); // 设置连接数据库需要的配置信息 bds.setDriverClassName("com.mysql.cj.jdbc.Driver"); bds.setUrl("jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8"); bds.setUsername("root"); bds.setPassword("root"); // 设置连接池的初始化连接参数 bds.setInitialSize(5); ds = bds; } ``` ### 4. 获得数据源和连接 1. 获得数据源 ``` public static DataSource getDs() { return ds; } ``` 2. 获得连接 ``` Connection conn = ds.getConnection(); ``` ## 问题05:c3p0数据库连接池的使用 ### 1. 导入jar包 ![](https://img.kancloud.cn/de/67/de67f289ed41f5f4dbfec2c55cc95f34_265x114.png) ### 2. 数据库信息配置 ![](https://img.kancloud.cn/7f/81/7f81c8337d5e81664826264b2bb2f06c_696x564.png) ### 3. 初始化数据源 > src根目录下创建一个c3p0-config.xml文件 ``` public static DataSource ds = new ComboPooledDataSource(); ``` ![](https://img.kancloud.cn/50/4e/504e4c1fba6e21b0f2f236db13b28d0d_881x435.png) ### 4. 获得数据源和连接 同上 ## 问题06:Druid数据库连接池的使用 ### 1. 导入jar包 ![](https://img.kancloud.cn/04/a2/04a236e18bf1a7cd8c00b53bb4b5b8e1_268x144.png) ### 2. 数据库信息配置 ![](https://img.kancloud.cn/07/ef/07efa91b6e8a0cb5822a7bfc85c47fca_423x144.png) ### 3. 初始化数据源 ``` ds = DruidDataSourceFactory.createDataSource(pro); ``` ### 4. 获得数据源和连接 同上