码迷,mamicode.com
首页 > 其他好文 > 详细

【C3P0】C3P0

时间:2021-03-06 15:09:12      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:连接   lis   name   enc   java   dbn   static   mave   ted   

1、resources目录下添加c3p0-config.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <c3p0-config>
 3     <!-- 默认配置,如果没有指定则使用这个配置 -->
 4     <default-config>
 5         <!-- 初始化池大小 -->
 6         <property name="initialPoolSize">2</property>
 7         <!-- 最大空闲时间 -->
 8         <property name="maxIdleTime">30</property>
 9         <!-- 最多有多少个连接 -->
10         <property name="maxPoolSize">10</property>
11         <!-- 最少几个连接 -->
12         <property name="minPoolSize">2</property>
13         <!-- 每次最多可以执行多少个批处理语句 -->
14         <property name="maxStatements">50</property>
15     </default-config>
16 
17     <!-- 命名的配置 -->
18     <named-config name="c3p0">
19         <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
20         <property name="jdbcUrl">jdbc:mysql://localhost:3306/c3p0?serverTimezone=CTT</property>
21         <property name="user">root</property>
22         <property name="password">root</property>
23         <property name="acquireIncrement">5</property><!-- 如果池中数据连接不够时一次增长多少个 -->
24         <property name="initialPoolSize">10</property>
25         <property name="minPoolSize">5</property>
26         <property name="maxPoolSize">200</property>
27         <property name="maxStatements">0</property>
28         <property name="maxStatementsPerConnection">5</property> <!-- hes important, but theres only one of him -->
29     </named-config>
30 
31     <!-- 命名的配置 -->
32     <named-config name="mybatis">
33         <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
34         <property name="jdbcUrl">jdbc:mysql://localhost:3306/mybatis?serverTimezone=CTT</property>
35         <property name="user">root</property>
36         <property name="password">root</property>
37         <property name="acquireIncrement">5</property><!-- 如果池中数据连接不够时一次增长多少个 -->
38         <property name="initialPoolSize">10</property>
39         <property name="minPoolSize">5</property>
40         <property name="maxPoolSize">200</property>
41         <property name="maxStatements">0</property>
42         <property name="maxStatementsPerConnection">5</property> <!-- hes important, but theres only one of him -->
43     </named-config>
44 </c3p0-config>

2、resources目录下添加log4j.properties配置文件

1 log4j.rootCategory=info,stdout
2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
3 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
4 log4j.appender.stdout.layout.ConversionPattern=%d{yyy MMM dd HH:mm:ss,SSS} %p [%t] %C.%M(%L) : %m%n

3、引入pom.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <project xmlns="http://maven.apache.org/POM/4.0.0" 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.sheep</groupId>
 8     <artifactId>c3p0-study</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10 
11     <name>c3p0-study</name>
12     <!-- FIXME change it to the project‘s website -->
13     <url>http://www.example.com</url>
14 
15     <properties>
16         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
17         <maven.compiler.source>1.8</maven.compiler.source>
18         <maven.compiler.target>1.8</maven.compiler.target>
19     </properties>
20 
21     <dependencies>
22         <dependency>
23             <groupId>junit</groupId>
24             <artifactId>junit</artifactId>
25             <version>4.11</version>
26             <scope>test</scope>
27         </dependency>
28 
29         <!-- https://mvnrepository.com/artifact/log4j/log4j -->
30         <dependency>
31             <groupId>log4j</groupId>
32             <artifactId>log4j</artifactId>
33             <version>1.2.17</version>
34         </dependency>
35 
36 
37         <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
38         <dependency>
39             <groupId>com.mchange</groupId>
40             <artifactId>c3p0</artifactId>
41             <version>0.9.5.4</version>
42         </dependency>
43 
44         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
45         <dependency>
46             <groupId>mysql</groupId>
47             <artifactId>mysql-connector-java</artifactId>
48             <version>8.0.22</version>
49         </dependency>
50 
51         <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
52         <dependency>
53             <groupId>org.projectlombok</groupId>
54             <artifactId>lombok</artifactId>
55             <version>1.18.16</version>
56             <scope>provided</scope>
57         </dependency>
58 
59         <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
60         <dependency>
61             <groupId>cn.hutool</groupId>
62             <artifactId>hutool-all</artifactId>
63             <version>5.5.9</version>
64         </dependency>
65 
66     </dependencies>
67 
68     <build>
69 
70         <resources>
71             <resource>
72                 <directory>src/main/resources</directory>
73                 <filtering>true</filtering>
74                 <includes>
75                     <include>**/*.xml</include>
76                     <include>**/*.properties</include>
77                 </includes>
78             </resource>
79             <resource>
80                 <directory>src/main/java</directory>
81                 <filtering>true</filtering>
82                 <includes>
83                     <include>**/*.xml</include>
84                     <include>**/*.properties</include>
85                 </includes>
86             </resource>
87         </resources>
88     </build>
89 </project>

4、编写DbUtils.java文件

  1 package com.sheep.utils;
  2 
  3 import cn.hutool.db.Db;
  4 import cn.hutool.db.StatementUtil;
  5 import cn.hutool.json.JSONArray;
  6 import cn.hutool.json.JSONException;
  7 import cn.hutool.json.JSONObject;
  8 import com.mchange.v2.c3p0.ComboPooledDataSource;
  9 
 10 import javax.sql.DataSource;
 11 import java.sql.*;
 12 import java.util.List;
 13 
 14 @SuppressWarnings("all")
 15 public class DbUtils {
 16 
 17     private static DataSource ds = null;
 18 
 19     private static DataSource getDataSource(String dbName) {
 20         //读取配置文件
 21         ds = new ComboPooledDataSource(dbName);
 22         return ds;
 23     }
 24 
 25     /**
 26      * 数据库增删改通用操作
 27      *
 28      * @param dbName
 29      * @param sql
 30      * @param params
 31      * @return
 32      */
 33     public static int update(String dbName, String sql, Object... params) {
 34         Db db = Db.use(DbUtils.getDataSource(dbName));
 35         int num = 0;
 36         try {
 37             num = db.execute(sql, params);
 38         } catch (SQLException e) {
 39             e.printStackTrace();
 40         }
 41         return num;
 42     }
 43 
 44     /**
 45      * 数据库查询操作,返回List集合
 46      *
 47      * @param dbName
 48      * @param sql
 49      * @param beanClass
 50      * @param params
 51      * @param <T>
 52      * @return
 53      */
 54     public static <T> List<T> query(String dbName, String sql, Class<T> beanClass, Object... params) {
 55         Db db = Db.use(DbUtils.getDataSource(dbName));
 56         List<T> list = null;
 57         try {
 58             list = db.query(sql, beanClass, params);
 59         } catch (SQLException e) {
 60             e.printStackTrace();
 61         }
 62         return list;
 63 
 64     }
 65 
 66     /**
 67      * 数据库查询操作,返回JSONArray
 68      *
 69      * @param dbName
 70      * @param sql
 71      * @param params
 72      * @return
 73      */
 74     public static JSONArray query(String dbName, String sql, Object... params) {
 75         Connection conn = null;
 76         PreparedStatement pst = null;
 77         ResultSet rs = null;
 78         try {
 79             conn = DbUtils.getDataSource(dbName).getConnection();
 80         } catch (SQLException e) {
 81             e.printStackTrace();
 82         }
 83         //新建JsonArray
 84         JSONArray jsonArray = new JSONArray();
 85         try {
 86             pst = StatementUtil.prepareStatement(conn, sql, params);
 87             rs = pst.executeQuery();
 88 
 89             ResultSetMetaData data = rs.getMetaData();
 90             while (rs.next()) {
 91                 JSONObject jsonObject = new JSONObject();
 92                 for (int i = 1; i <= data.getColumnCount(); ++i) {
 93                     //列名
 94                     String columnName = data.getColumnName(i);
 95                     String rst = rs.getString(i);
 96                     jsonObject.put(columnName, rst);
 97                 }
 98                 jsonArray.put(jsonObject);
 99             }
100 
101         } catch (SQLException e) {
102             // TODO Auto-generated catch block
103             e.printStackTrace();
104         } catch (JSONException e) {
105             // TODO Auto-generated catch block
106             e.printStackTrace();
107         }
108         DbUtils.close(conn, pst, rs);
109         return jsonArray;
110     }
111 
112     private static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
113         if (null != rs) {
114             try {
115                 rs.close();
116             } catch (SQLException e) {
117                 e.printStackTrace();
118             }
119         }
120         if (null != pst) {
121             try {
122                 pst.close();
123             } catch (SQLException e) {
124                 e.printStackTrace();
125             }
126         }
127         if (null != conn) {
128             try {
129                 conn.close();
130             } catch (SQLException e) {
131                 e.printStackTrace();
132             }
133         }
134     }
135 }

5、编写Student实体类

 1 package com.sheep.domain;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Data;
 5 import lombok.NoArgsConstructor;
 6 import lombok.ToString;
 7 
 8 @Data
 9 @ToString
10 @NoArgsConstructor
11 @AllArgsConstructor
12 public class Student {
13 
14     private Integer id;
15     private String name;
16     private String email;
17     private Integer age;
18 }

6、编写测试类

 1 package com.sheep;
 2 
 3 import cn.hutool.json.JSONArray;
 4 import com.sheep.domain.Student;
 5 import com.sheep.utils.DbUtils;
 6 import org.apache.log4j.Logger;
 7 import org.junit.Test;
 8 
 9 import java.util.List;
10 
11 /**
12  * Unit test for simple App.
13  */
14 public class AppTest {
15     private static Logger logger = Logger.getLogger(AppTest.class);
16 
17     /**
18      * 测试查询,返回集合
19      */
20     @Test
21     public void testA() {
22         String sql = "select * from  t_student where id=?";
23         List<Student> students = DbUtils.query("c3p0", sql, Student.class, "1001");
24         students.forEach(s -> logger.info(s));
25     }
26 
27 
28     /**
29      * 测试查询,返回JSON数组
30      */
31     @Test
32     public void testC() {
33         String sql = "select * from  t_student where id >= ?";
34         JSONArray jsonArray = DbUtils.query("c3p0", sql, 1001);
35         jsonArray.forEach(s -> logger.info(s));
36     }
37 
38     /**
39      * 测试增删改
40      */
41     @Test
42     public void testB() {
43         String s1 = "insert into  t_student values(?,?,?,?)";
44         DbUtils.update("c3p0", s1, 1003, "王五", "wangwu@qq.com", 35);
45 
46         String s2 = "delete from  t_student where id=?";
47         DbUtils.update("c3p0", s2, 1003);
48 
49         String s3 = "update   t_student  set age=? where id=?";
50         DbUtils.update("c3p0", s3, 10, 1001);
51 
52     }
53 
54 }

完结。。。

【C3P0】C3P0

标签:连接   lis   name   enc   java   dbn   static   mave   ted   

原文地址:https://www.cnblogs.com/sheep9527/p/14490241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!