dbcp
1.引入jar包
导入这两个jar包
下载jar包地址:Maven Repository: Search/Browse/Explore (mvnrepository.com)
(进入网站后,可直接在搜索框中搜索下载)
[En]
(after entering the website, you can search and download directly in the search box)
2.配置后缀为 .properties 文件
如例:
1 #
2 driverClassName=com.mysql.cj.jdbc.Driver
3 url=jdbc:mysql://localhost:3306/test02
4 username=root
5 password=root
6
7 #
8 initialSize=10
9
10 #
11 maxActive=50
12
13 #
14 maxIdle=20
15
16 #
17 minIdle=5
18
19 #
20 maxWait=50000
21
22 #
23 connectionProperties=useUnicode=true;characterEncoding=utf8
24
25 ##
26 defaultAutoCommit=true
27
28 #
29 defaultTransactionIsolation=REPEATABLE_READ
3.创建utils包(获取connection,释放连接资源)
1 public class JdbcUtils_c3p0 {
2
3 private static DataSource dataSource;
4 static {
5 try {
6
7 //创建数据源 工厂模式 --》创建
8 dataSource = new ComboPooledDataSource();
9
10
11 } catch (Exception e) {
12 e.printStackTrace();
13 }
14 }
15
16 //获取连接
17 public static Connection getConnection() throws Exception{
18 return dataSource.getConnection();
19
20 }
21 //释放链接资源
22 public static void release(Connection connection, Statement statement, ResultSet resultSet){
23 try {
24 if (resultSet != null) {
25 resultSet.close();
26 }
27 if (statement != null) {
28 statement.close();
29 }
30 if (connection != null) {
31 connection.close();
32 }
33 }catch (Exception e){
34 e.printStackTrace();
35 }
36 }
37 }
4.测试
(我在这里添加一段数据作为示例。)
[En]
(I’m here to add a piece of data as an example.)
1 Connection connection = null;
2 PreparedStatement ps = null;
3 ResultSet resultSet =null;
4 //1.获取数据库连接
5 try {
6 connection = JdbcUtils_c3p0.getConnection();
7 String sql = "insert into student (name,sex,birthday,tall) values (?,?,?,?)";
8 ps = connection.prepareStatement(sql); //预编译sql 先写sql,然后不执行
9 //手动为参数赋值
10 ps.setString(1, "嗷嗷嗷");
11 ps.setString(2, "男");
12 ps.setString(3, "2002.1.8");
13 ps.setDouble(4, 1.75);
14 //执行
15 ps.executeUpdate();
16
17 } catch (Exception e) {
18 e.printStackTrace();
19 } finally {
20 JdbcUtils.release(connection, ps, resultSet);
21 }
22 }
Original: https://www.cnblogs.com/qiaoyuqi/p/15780855.html
Author: 咸鱼乔
Title: 数据连接池
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/507890/
转载文章受原作者版权保护。转载请注明原作者出处!