JDBCUtils中使用C3P0数据库连接池获取连接

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2023年1月12日 (四) 06:49的版本 →‎测试新的 JDBCUtils
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1eJ411c7rf?p=48

新的 JDBCUtils

package io.github.jihch.betterutil;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils {

    private static ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0");

    /**
     * 使用C3P0连接池技术
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = cpds.getConnection();
        return conn;
    }

    /**
     * 关闭连接和 Statement 的操作
     * @param conn
     * @param ps
     */
    public static void closeResource(Connection conn, Statement ps){
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }



}



测试新的 JDBCUtils

package io.github.jihch.betterutil;

import io.github.jihch.bean.Customer;
import io.github.jihch.betterdao.CustomerDAOImpl;
import org.junit.Test;

import java.sql.Connection;
import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.*;

public class JDBCUtilsTest {

    private CustomerDAOImpl dao = new CustomerDAOImpl();

    @Test
    public void getConnection1() {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            Customer customer = dao.getCustomerById(con, 4);
            System.out.println(customer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(con, null);
        }
    }

    /**
     * 每次 connnection 的 hashcode 都不同,怎么判断 connnection 被重用了?
     */
    @Test
    public void getConnection2() {
        Connection con = null;
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < 100; i++) {
            try {
                con = JDBCUtils.getConnection();
                set.add(con.hashCode());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtils.closeResource(con, null);
            }
        }
        set.forEach(System.out::println);
    }
}

https://github.com/jihch/jdbc_2/blob/main/src/main/java/io/github/jihch/betterutil/JDBCUtils.java

https://github.com/jihch/jdbc_2/blob/main/src/test/java/io/github/jihch/betterutil/JDBCUtilsTest.java