【JDBC】C3P0连接池的使用

C3P0连接池的c3p0-config.xml配置文件



    
        com.mysql.cj.jdbc.Driver
        jdbc:mysql:///jdbctest?serverTimezone=Hongkong
        root
        1234
        5
        20
    

工具类

package jdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {
    private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
    
    public static Connection getConection() throws Exception {
        return cpds.getConnection();
    }
    
    public static void release(Statement stmt, Connection conn) {
        if(stmt != null) {
            try {
                stmt.close();
            }catch(Exception e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        
        if(conn != null) {
            try {
                conn.close();
            }catch(Exception e) {
                e.printStackTrace();
            }
            conn = null;
        }       
    }
    
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        if(rs != null) {
            try {
                rs.close();
            }catch(Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        
        if(stmt != null) {
            try {
                stmt.close();
            }catch(Exception e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        
        if(conn != null) {
            try {
                conn.close();
            }catch(Exception e) {
                e.printStackTrace();
            }
            conn = null;
        }       
    }
}

单元测试

package demo1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import jdbcUtils.JDBCUtils;

public class JDBCDemo4 {
    
    @Test
    public void demo4() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 获得连接
            conn = JDBCUtils.getConection();
            // 编写SQL
            String sql = "select * from course";
            // 预编译SQL
            pstmt = conn.prepareStatement(sql);
            // 执行SQL
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt("id") + " " + rs.getString("name") + " " + rs.getString("category") + " "
                        + rs.getString("desp") + " " + rs.getTimestamp("createTime"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, pstmt, conn);
        }
    }
}

你可能感兴趣的:(【JDBC】C3P0连接池的使用)