05-c3p0连接池

1. 导入 jar 包

jar包下载地址:https://mvnrepository.com/

image-20230316140933140
导入IDEA,位置:project\lib
image-20230316140944384

2. 配置文件

位置:project\src\c3p0.properties

1
2
3
4
5
# MySQL c3p0 数据库配置
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/数据库名
c3p0.user=root
c3p0.password=123456

3. 连接池工具类

C3P0DbUtils.java

1
2
3
4
5
6
7
8
9
10
11
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0DbUtils {
private static ComboPooledDataSource dataSource;
static {
dataSource = new ComboPooledDataSource();
}

public static ComboPooledDataSource getDataSource() {
return dataSource;
}
}

4. 执行SQL语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class UserDaoImpl implements UserDao {
private QueryRunner queryRunner = new QueryRunner(C3P0dbUtils.getDataSource());

/**
* 增删改操作
* @param action 字符串insert/delete/update
* @param user 操作的用户
* @return 影响结果行
*/
@Override
public int update(String action, User user) throws SQLException {
if (null == action) {
return -1;
}

String sql = null;
Object[] args = null;
if ("insert".equals(action)) {
sql = "insert into userinfo(username, password) value(?,?)";
args = new Object[]{user.getUsername(), user.getPassword()};
} else if ("delete".equals(action)) {
sql = "delete from userinfo where id=?";
args = new Object[]{user.getId()};
} else if ("update".equals(action)) {
sql = "update userinfo set username=?,password=? where id=?";
args = new Object[]{user.getUsername(), user.getPassword(), user.getId()};
} else {
return -1;
}
System.out.println("sql=" + sql);
System.out.println("args=" + args);
return queryRunner.update(Objects.requireNonNull(sql), args);
}

/**
* 查单个
* @param id 编号
* @return 用户对象
*/
@Override
public User select(Integer id) throws SQLException {
return queryRunner.query(
"select * from userinfo where id=?",
new BeanHandler<>(User.class),
id
);
}

/**
* 查所有
* @return 对象表
*/
@Override
public List<User> selectALL() throws SQLException {
return queryRunner.query(
"select * from userinfo",
new BeanListHandler<>(User.class)
);
}
}

05-c3p0连接池
https://janycode.github.io/2016/04/28/02_编程语言/01_Java/03_JDBC/05-c3p0连接池/
作者
Jerry(姜源)
发布于
2016年4月28日
许可协议