Loading

常用数据库连接池配置及使用(Day_11)

 

            世上没有从天而降的英雄,只有挺身而出的凡人。

                      ——致敬,那些在疫情中为我们挺身而出的人。

 


 

  • 运行环境

 

 JDK8 + IntelliJ IDEA 2018.3 

 

优点:

使用连接池的最主要的优点是性能。创建一个新的数据库连接所耗费的时间主要取决于网络的速

度以及应用程序和数据库服务器的(网络)距离,而且这个过程通常是一个很耗时的过程。而采用

数据库连接池后,数据库连接请求可以直接通过连接池满足而不需要为该请求重新连接、认证到

数据库服务器,这样就节省了时间。

 

缺点:

数据库连接池中可能存在着多个没有被使用的连接一直连接着数据库(这意味着资源的浪费)

 

一、导包

  xml文件:

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.papercy</groupId>
 8     <artifactId>DBCP</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10     <dependencies>
11         <dependency>
12             <groupId>mysql</groupId>
13             <artifactId>mysql-connector-java</artifactId>
14             <version>5.1.48</version>
15         </dependency>
16 
17         <!--C3P0-->
18         <dependency>
19             <groupId>c3p0</groupId>
20             <artifactId>c3p0</artifactId>
21             <version>0.9.1.1</version>
22         </dependency>
23           <!--DBCP   -->
24         <dependency>
25             <groupId>commons-dbcp</groupId>
26             <artifactId>commons-dbcp</artifactId>
27             <version>1.4</version>
28         </dependency>
29 
30         <dependency>
31             <groupId>commons-pool</groupId>
32             <artifactId>commons-pool</artifactId>
33             <version>1.5.7</version>
34         </dependency>
35 
36         <dependency>
37             <groupId>junit</groupId>
38             <artifactId>junit</artifactId>
39             <version>4.13</version>
40         </dependency>
41 
42         <!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java -->
43         <dependency>
44             <groupId>com.mchange</groupId>
45             <artifactId>mchange-commons-java</artifactId>
46             <version>0.2.15</version>
47         </dependency>
48     </dependencies>
49 
50 </project>

 

二、DBCP

DBUtil 类

 1 package com.papercy;
 2 
 3 import org.apache.commons.dbcp.BasicDataSource;
 4 
 5 public class DBCPUtils {
 6     private static String DRIVER="com.mysql.jdbc.Driver";
 7     private static String URL="jdbc:mysql://localhost/lob?useUnicode=true&characterEncoding=utf8";
 8     private static String USERNAME="root";
 9     private static String PASSWORD="123456";
10 
11     //获取BasicDataSource并配置,开始.... 
12     private static BasicDataSource basicDataSource=new BasicDataSource();
13     static {
14         basicDataSource.setUrl(URL);
15         basicDataSource.setUsername(USERNAME);
16         basicDataSource.setPassword(PASSWORD);
17         basicDataSource.setInitialSize(10);//初始化创建十个链接
18         basicDataSource.setMaxActive(10);//允许同时10个活动连接数
19         basicDataSource.setMaxIdle(8);//最大空闲连接数
20         basicDataSource.setMinIdle(1);//最小空闲连接数
21 
22     }
23 
24     public static BasicDataSource getBasicDataSource(){
25         return basicDataSource;
26     }
27 }

 

 测试类

 1 package com.papercy;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.SQLException;
 6 
 7 public class TestDBUtil {
 8     public static void main(String[] args) {
 9         try {
10             Connection conn=DbcpDBUtil.getDataSource().getConnection();
11             String sql="INSERT INTO student(id,`name`,age) VALUES(NULL,?,?)";
12             PreparedStatement preparedStatement=conn.prepareStatement(sql);
13             preparedStatement.setString(1,"feifeiye");
14             preparedStatement.setInt(2,88);
15             int count=preparedStatement.executeUpdate();
16 
17             if (count>0){
18                 System.out.println("插入成功");
19             }else{
20                 System.out.println("插入失败");
21             }
22 
23         } catch (SQLException e) {
24             e.printStackTrace();
25         }
26     }
27 }

 

注:其中的Close方法不会真正的将连接关闭,而是将其放回到连接池中,对于所有的数据源一般都会改写此方法(使用修饰)。

 

方式二:使用BasicDataSourceFactory +配置文件

配置文件dbcp.properties:

1 diverClassName=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/lob?useUnicode=true&characterEncoding=utf8
3 user=root
4 pwd=123456

 

 

 1 package com.papercy;
 2 
 3 import org.apache.commons.dbcp.BasicDataSourceFactory;
 4 
 5 
 6 import javax.sql.DataSource;
 7 import java.io.FileInputStream;
 8 import java.io.FileNotFoundException;
 9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.util.Properties;
12 
13 public class DbcpDBUtil {
14     public static DataSource getDataSource(){
15         Properties properties=new Properties();
16         String path="src/dbcp.properties";
17         try {
18             InputStream inputStream=new FileInputStream(path);
19             properties.load(inputStream);
20         } catch (FileNotFoundException e) {
21             e.printStackTrace();
22         } catch (IOException e) {
23             e.printStackTrace();
24         }
25 
26 
27         DataSource dataSource=null;
28         try {
29             dataSource= new BasicDataSourceFactory().createDataSource(properties);
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33         return dataSource;
34     }
35 }

 

 

三、C3P0


C3P0Util类
 1 package com.papercy.c3p0;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 
 5 import javax.sql.DataSource;
 6 import java.sql.Connection;
 7 import java.sql.PreparedStatement;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 
11 /**
12  * C3P0工具类
13  */
14 public class C3p0Utils {
15     //定义数据源对象
16     private static DataSource dataSource;
17     //获取数据源
18     static {
19         dataSource=new ComboPooledDataSource();
20     }
21     //通过数据源获取数据库连接
22     public static Connection getConnection(){
23         try {
24             return dataSource.getConnection();
25         } catch (SQLException e) {
26             e.printStackTrace();
27             return null;
28         }
29     }
30     //关闭预处理对象和结果集对象
31     public static void close(PreparedStatement preparedStatement, ResultSet resultSet){
32         if (resultSet!=null){
33             try {
34                 resultSet.close();
35             } catch (SQLException e) {
36                 e.printStackTrace();
37             }
38         }
39 
40         if (preparedStatement!=null){
41             try {
42                 preparedStatement.close();
43             } catch (SQLException e) {
44                 e.printStackTrace();
45             }
46         }
47 
48     }
49 }

 

C3P0测试类

 1 package com.papercy.c3p0;
 2 
 3 import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
 4 
 5 import java.sql.Connection;
 6 import java.sql.PreparedStatement;
 7 import java.sql.ResultSet;
 8 import java.sql.SQLException;
 9 
10 /**
11  * 测试C3P0
12  */
13 public class TestC3p0Pools {
14     public static void main(String[] args) {
15         Connection conn=C3p0Utils.getConnection();
16         String sql="SELECT * FROM EMPLOYEES";
17         PreparedStatement preparedStatement=null;
18         ResultSet resultSet=null;
19         try {
20              preparedStatement=conn.prepareStatement(sql);
21              resultSet=preparedStatement.executeQuery();
22             while(resultSet.next()){
23                 int id=resultSet.getInt("EID");
24                 String firstName=resultSet.getString("FIRSTNAME");
25                 String lastName=resultSet.getString("LASTNAME");
26                 int age=resultSet.getInt("AGE");
27                 System.out.println(id+"\t"+firstName+"\t"+lastName+"\t"+age);
28             }
29         } catch (SQLException e) {
30             e.printStackTrace();
31         }finally {
32             C3p0Utils.close(preparedStatement,resultSet);
33         }
34     }
35 }

 

注:

  1. acquireIncrement: 声明当连接池中连接耗尽时再一次新生成多少个连接,默认为3个
  2. initialPoolSize:      当连接池启动时,初始化连接的个数,必须在minPoolSize~maxPoolSize之间,默认为3
  3. minPoolSize:        任何时间连接池中保存的最小连接数,默认3
  4. maxPoolSize:       在任何时间连接池中所能拥有的最大连接数,默认15
  5. maxIdleTime:        超过多长时间连接自动销毁,默认为0,即永远不会自动销毁

 


 

PS:

 

如果,您希望更容易地发现我的新博客,不妨点击一下关注。

 

如果你觉得本篇文章对你有所帮助,请给予我更多的鼓励,

 

因为,我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【肥肥也】!

 

posted @ 2020-09-09 18:51  A零号  阅读(298)  评论(0编辑  收藏  举报