因不想继续在PHP花更多的时间,所以入手JAVA,从零学至此利用C3P0实现JDBC连接池,提高数据库处理的能力,加快性能。一般情况下,操作数据库的过程都是连接数据库->执行操作->释放资源。这样的操作在一般情况下是没什么问题的,但是如果出现频繁的操作就会造成一些性能上的问题,因为频繁打开关闭连接是个耗时的操作,所以就Java目前用得最多的是C3P0实现JDBC连接池,由于刚入手Java希望各位小伙伴海涵。
使用C3P0先得引包:c3p0-0.9.1.2.jar和mysql-connector-java-5.1.39-bin.jar
编写C3P0配置文件c3p0-config.xml
<?xml version="1.0" encoding="UTF-8" ?><c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test20180109</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <named-config name="lfriend"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///test20180109</property> <property name="user">root</property> <property name="password">root</property> </named-config></c3p0-config>
编写c3p0工具类
package me.lfriend.jdbc.utils;import com.mchange.v2.c3p0.ComboPooledDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;public class C3P0Utils { private static ComboPooledDataSource dataSource=new ComboPooledDataSource('lfriend'); public static DataSource getDataSource(){ return dataSource; } public static Connection getConnection(){ try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } }}
编写测试类TestC3P0.java
package me.lfriend.jdbc.test;import com.mchange.v2.c3p0.ComboPooledDataSource;import me.lfriend.jdbc.utils.C3P0Utils;import me.lfriend.jdbc.utils.JDBCUtils_V3;import org.junit.Test;import java.sql.Connection;import java.sql.PreparedStatement;public class TestC3P0 { @Test public void testAddUser(){ Connection conn=null; PreparedStatement pstmp=null; //1.创建自定义连接池对象 ComboPooledDataSource dataSource=new ComboPooledDataSource();//加载默认配置 //ComboPooledDataSource dataSource=new ComboPooledDataSource("lfriend");//加载有名称的配置 try { //2.从池子中获取连接 conn=dataSource.getConnection(); //3.编写sql String sql="insert into user values(null,?,?)"; //4.创建预处理对象 pstmp=conn.prepareStatement(sql); //5.设置参数 pstmp.setString(1,"piu"); pstmp.setString(2,"123456"); //6.执行查询 int row=pstmp.executeUpdate(); if(row>0){ System.out.println("添加成功!"); }else{ System.out.println("添加失败!"); } }catch (Exception e){ throw new RuntimeException(e); }finally { JDBCUtils_V3.release(conn,pstmp,null); } } /** * 工具类使用C3P0 */ @Test public void testAddUser1(){ Connection conn=null; PreparedStatement pstmp=null; try { conn= C3P0Utils.getConnection(); //3.编写sql String sql="insert into user values(null,?,?)"; //4.创建预处理对象 pstmp=conn.prepareStatement(sql); //5.设置参数 pstmp.setString(1,"piu"); pstmp.setString(2,"123456"); //6.执行查询 int row=pstmp.executeUpdate(); if(row>0){ System.out.println("添加成功!"); }else{ System.out.println("添加失败!"); } }catch (Exception e){ throw new RuntimeException(e); }finally { JDBCUtils_V3.release(conn,pstmp,null); } }}
C3P0的基本操作就是这样,欢迎各位大佬指出问题!