JavaEE基础(06):Servlet整合C3P0数据库连接池
本文源码:GitHub·点这里 || GitEE·点这里
一、C3P0连接池
1、C3P0简介
C3P0是一个开源的JDBC连接池,应用程序根据C3P0配置来初始化数据库连接,可以自动回收空闲连接的功能。
2、核心依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
3、配置文件
配置文件位置:放在resources目录下,这样C3P0组件会自动加载该配置。
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<!-- 核心参数配置 -->
<property name="jdbcUrl">jdbc:mysql://localhost:3306/servlet-jdbc</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">123</property>
<!-- 池参数配置 -->
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
4、编写工具类
该工具类用来获取数据库连接,和释放相关连接。
public class C3P0Pool {
private static DataSource dataSource = new ComboPooledDataSource();
public static DataSource getDataSource() {
return dataSource ;
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 释放连接
*/
public static void close(ResultSet resultSet, PreparedStatement pst, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
二、数据操作封装
1、新增数据
public class UserJdbcInsert {
public static void insertUser (UserInfo userInfo){
try {
Connection connection = C3P0Pool.getConnection();
String sql = "INSERT INTO user_info (user_name,user_age) VALUES (?,?)" ;
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,userInfo.getUserName());
statement.setString(2,userInfo.getUserAge().toString());
statement.execute() ;
C3P0Pool.close(null, statement, connection);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void batchInsertUser (List<UserInfo> userInfoList){
try {
Connection connection = C3P0Pool.getConnection();
String sql = "INSERT INTO user_info (user_name,user_age) VALUES (?,?)" ;
PreparedStatement statement = connection.prepareStatement(sql);
for (UserInfo userInfo:userInfoList){
statement.setString(1,userInfo.getUserName());
statement.setString(2,userInfo.getUserAge().toString());
statement.addBatch();
}
statement.executeBatch() ;
C3P0Pool.close(null, statement, connection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、查询数据
public class UserJdbcQuery {
public static UserInfo queryUser (String userName){
UserInfo userInfo = null ;
try {
Connection connection = C3P0Pool.getConnection();
String sql = "SELECT * FROM user_info WHERE user_name=?" ;
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,userName);
ResultSet resultSet = statement.executeQuery() ;
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("user_name");
int age = resultSet.getInt("user_age");
System.out.println("ID:"+id+";name:"+name+";age:"+age);
userInfo = new UserInfo(name,age) ;
}
C3P0Pool.close(resultSet, statement, connection);
} catch (Exception e) {
e.printStackTrace();
}
return userInfo ;
}
}
3、更新数据
public class UserJdbcUpdate {
public static void updateUser (String name,Integer age,Integer id){
try {
Connection connection = C3P0Pool.getConnection();
String sql = "UPDATE user_info SET user_name=?,user_age=? WHERE id=?" ;
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,name);
statement.setInt(2,age);
statement.setInt(3,id);
statement.executeUpdate() ;
C3P0Pool.close(null, statement, connection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、删除数据
public class UserJdbcDelete {
public static void deleteUser (Integer id){
try {
Connection connection = C3P0Pool.getConnection();
String sql = "DELETE FROM user_info WHERE id=?" ;
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);
statement.executeUpdate() ;
C3P0Pool.close(null, statement, connection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、Servlet接口
public class JdbcServletImpl extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName") ;
UserInfo userInfo = UserJdbcQuery.queryUser(userName) ;
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("用户信息:"+userInfo);
}
}
测试访问:
http://localhost:6003/jdbcServletImpl?userName=LiSi
页面打印:
用户信息:UserInfo{userName='LiSi', userAge=22}
四、源代码地址
GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

JavaEE基础(06):Servlet整合C3P0数据库连接池的更多相关文章
- JDBC整合c3p0数据库连接池 解决Too many connections错误
前段时间,接手一个项目使用的是原始的jdbc作为数据库的访问,发布到服务器上在运行了一段时间之后总是会出现无法访问的情况,登录到服务器,查看tomcat日志发现总是报如下的错误. Caused by: ...
- C3P0数据库连接池使用方法
一.应用程序直接获取数据库连接的缺点 用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长.假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大 ...
- c3p0数据库连接池无法连接数据库—错误使用了username关键字
一.问题描述 上篇博客说到了关于maven无法下载依赖jar包的问题,这篇博客再说一下关于在本个项目中遇到的关于使用C3P0连接池连接数据库的问题,真心很奇葩,在此,也请大家引起注意.首先看我的项目基 ...
- 【Java EE 学习 16 上】【dbcp数据库连接池】【c3p0数据库连接池】
一.回顾之前使用的动态代理的方式实现的数据库连接池: 代码: package day16.utils; import java.io.IOException; import java.lang.ref ...
- paip.c3p0 数据库连接池 NullPointerException 的解决...
paip.c3p0 数据库连接池 NullPointerException 的解决... 程序ide里面运行正常..外面bat运行错误.. 作者Attilax 艾龙, EMAIL:14665198 ...
- paip.提升稳定性---c3p0数据库连接池不能取到连接An attempt by a client to checkout a Connection has timed out
paip.提升稳定性---c3p0数据库连接池不能取到连接An attempt by a client to checkout a Connection has timed out 作者Attilax ...
- [原创]java WEB学习笔记80:Hibernate学习之路--- hibernate配置文件:JDBC 连接属性,C3P0 数据库连接池属性等
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- c3p0数据库连接池(作用不重复)
/* * c3p0数据库连接池: * 只被初始化一次 * connection对象进行close时,不是正的关闭,而是将该数据连接归还给数据库连接池 * * */ 四个架包 mysql-connect ...
- springboot 使用c3p0数据库连接池
springboot 使用c3p0数据库连接池的方法 本文转自:http://www.cnblogs.com/xiaosiyuan/p/6255292.html 使用springboot开发时,默认 ...
随机推荐
- 最新版 IDEA 2019.2.4 下载安装 & 破解使用期限至2089年
一.准备 官网下载链接:https://www.jetbrains.com/idea/download/#section=windows 根据自己系统选择对应版本,这里选择Windows的UItima ...
- SpringBoot学习(二)—— springboot快速整合spring security组件
Spring Security 简介 spring security的核心功能为认证(Authentication),授权(Authorization),即认证用户是否能访问该系统,和授权用户可以在系 ...
- WebSocket网络通信协议
WebSocket 协议在2008年诞生,2011年成为国际标准.所有浏览器都已经支持了. HTTP 协议有一个缺陷:通信只能由客户端发起.这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端 ...
- javescript 的 对象
一,定义:对象是JavaScript的一个基本数据类型,是一种复合值,它将很多值(原始值或者其他对象)聚合在一起,可通过名字(name/作为属性名)访问这些值.即属性的无序集合. 关键是name属性名 ...
- 从零开始入门 | Kubernetes 中的服务发现与负载均衡
作者 | 阿里巴巴技术专家 溪恒 一.需求来源 为什么需要服务发现 在 K8s 集群里面会通过 pod 去部署应用,与传统的应用部署不同,传统应用部署在给定的机器上面去部署,我们知道怎么去调用别的机 ...
- PHP中16个高危函数
php中内置了许许多多的函数,在它们的帮助下可以使我们更加快速的进行开发和维护,但是这个函数中依然有许多的函数伴有高风险的,比如说一下的16个函数不到万不得已不尽量不要使用,因为许多“高手”可以通过这 ...
- Paramiko的SSH和SFTP使用
目录 1. 概述 2. Paramiko的基本使用 2.1 SSHClient关键参数介绍 2.2 SSHClient常用示例 2.2.1 通过用户名和密码方式登陆: 2.2.2 通过用户名和密码方式 ...
- 计蒜客 The Preliminary Contest for ICPC Asia Nanjing 2019
F Greedy Sequence You're given a permutation aa of length nn (1 \le n \le 10^51≤n≤105). For each ...
- 顺序栈与两栈共享空间-C语言实现
栈是一种只能允许在栈顶插入数据与删除数据的数据结构,其实这就是一种特殊的线性表,特殊在 只能在表尾进行增减元素,上代码 #include <stdio.h> #define MAXSIZE ...
- Unity3D 卡通描边之控制线条粗细
一.前言 之前我发表过一篇Unity3D 卡通渲染 基于退化四边形的实时描边,最重要的实时描边已经实现了,本文接下来要完善一下它. 在之前的实时描边中,使用了几何着色器中的LineStream来进行绘 ...