Mysql配置C3P0



需要导入的包

  • c3p0-0.9.5.2.jar
  • mchange-commons-0.2.15.jar
  • mysql-connector.jar


1. 配置xml

创建c3p0-config.xml文件,名字不能改动,并且放到src下,c3p0包会自动到src下查找c3p0-config.xml,名字错了,地方不对都不能配置成功


配置


    
    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/test
        root
        
        5
        10
        10
        50
        5
        5
    

或者到官网查看标准配置 C3P0

Mysql配置C3P0_第1张图片


2. C3P0Util工具类

public class C3P0Util {
    
    private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    
    public static Connection getConnection(){
        try {
            return comboPooledDataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}


3. 测试

public class Test {
    
    public static void main(String[] args) {
        
        //这里的关闭函数被c3p0动态代理了,被改写为放入连接池
        try(Connection conn = C3P0Util.getConnection()) {
            String sql = "INSERT INTO  account (`money`) VALUES (100)";
            PreparedStatement ps =  conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            if (ps.executeUpdate() > 0){
                ResultSet rs1 = ps.getGeneratedKeys();
                while(rs1.next()){
                    System.out.println(rs1.getInt(1));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

输出结果

9  
s#返回的主键
#测试成功




你可能感兴趣的:(Mysql配置C3P0)