JDBC知识学习——事务、dbcp连接池及c3p0连接池

一:事务

①事务:一组逻辑操作单元,使数据从一种状态变换到另一种状态并保证数据的一致性。原子性、一致性、隔离性、持久性。
②隔离级别:读未提交数据READ UNCOMMITTED、读已提交数据READ COMMITTED、可重复读REPEATABLE READ、串行化SERIALIZABLE。
③在当前的cmd窗口中查看MySQL隔离级别:select @@tx_isolation
设置当前MySQL连接的隔离级别:set transaction isolation level read committed
设置数据库系统的全局 隔离级别:set global transaction isolation level committed
代码示例:

public class BussinessTest {
    @Test
    public  void TestTransaction(){
        Connection connection=null;
        try {
            connection=JDBCTools.getConnection();
            //事务开始,取消默认提交
            connection.setAutoCommit(false);
            String sql1="";
            update(connection,sql1);
            String sql2="";
            update(connection,sql2);
            //提交事务
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                //回滚事务
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
JDBCTools.releaseSource(null,null,connection);
        }
    }
    @Test
    public void testBatch(){
        /*
        * 批量处理sql提高执行速度和效率
        * */
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql=null;
        try {
            connection=JDBCTools.getConnection();
            //开始事务
            connection.setAutoCommit(false);
             sql="insert into user values(?,?)";
            preparedStatement=connection.prepareStatement(sql);
            long beginTime=System.currentTimeMillis();
            for (int i = 0; i < 100000; i++) {
                preparedStatement.setInt(1,i+1);
                preparedStatement.setString(2,"name_"+i);
                //储蓄要执行的sql
                preparedStatement.addBatch();
                if((i+1)%200 ==0){
                    //积累到200条是统一执行
                    preparedStatement.executeBatch();
                    //执行完成后清空
                    preparedStatement.clearBatch();
                }
            }
            long endTime=System.currentTimeMillis();
            System.out.println(endTime-beginTime);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCTools.releaseSource(null,preparedStatement,connection);
        }
    }
/**
*@ClassName BussinessTest
*@Description 执行sql的方法
*@Param [connection, sql, args]
*@Return void
*@Date 2020/2/17 15:52
*@Author Roy
*/
    public void update(Connection connection,String sql,Object ... args){
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement=connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            preparedStatement.executeUpdate();
        }catch (Exception e){
        e.printStackTrace();
        }finally {
        JDBCTools.releaseSource(null,preparedStatement,null);
        }
    }
}

二:dbcp连接池使用

注意: 加入jar包commons-dbcp.jar且依赖于commons-pool-1.5.6.jar包
代码使用示例:

public class PoolTest {
    /*
    * dbcp factory测试
    * */
    @Test
    public void testDbcpFactory() throws Exception {
        Properties properties=new Properties();
        //文件输入流
        InputStream in=PoolTest.class.getClassLoader().getResourceAsStream("dbcp.properties");
        properties.load(in);
        //创建连接属性
        DataSource dataSource=BasicDataSourceFactory.createDataSource(properties);
        //获取连接
        Connection connection=dataSource.getConnection();
        System.out.println(connection);
    }

    /*
    *使用DBCP数据库连接池
    * 加入jar包commons-dbcp.jar且依赖于commons-pool-1.5.6.jar包
     *  */
    @Test
    public void testDBCP(){
        BasicDataSource dataSource=null;
        //创建实例
        dataSource=new BasicDataSource();
        //指定连接属性
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //指定数据库连接池中初始化连接的数量
        dataSource.setInitialSize(8);
        //指定最大的连接数:指同时可以向数据库申请的连接数
        dataSource.setMaxActive(40);
        //指定最小连接:指连接池保存的最少的空闲连接的数量
        dataSource.setMinIdle(3);
        //最长的等待时间:等待数据库分配连接的最长时间毫秒
        dataSource.setMaxWait(2000);

        //获取连接
        try {
            Connection connection=dataSource.getConnection();
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

三:c3p0连接池使用

使用c3p0数据源
①:导入c3p0-0.9.2.1.jar文件并创建c3p0-config.xml配置文件
②:创建c3p0-config.xml配置文件在module显得src下创建file命名为:c3p0-config.xml。
并在此文件中输入以下配置:

<c3p0-config>
    <named-config name="hello">
        <!--连接数据库的基本属性-->
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
        <!--若数据库中连接数不足时,一次向数据库服务器申请多少个连接-->
        <property name="acquireIncrement">5</property>
        <!--初始化连接数据库连接池的数量-->
        <property name="initialPoolSize">10</property>
        <!--初始化连接池中的最小数据库连接数-->
        <property name="minPoolSize">5</property>
        <!--初始化连接池中的最大数据库连接数-->
        <property name="maxPoolSize">10</property>
        <!--数据库连接池可以维护的Statement的个数-->
        <property name="maxStatement">0</property>
        <!--每个连接可以同时使用Statement对象的个数-->
        <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config>

现在即可以使用代码测试:

public class c3p0Test {
    //使用配置文件连接
    @Test
    public void testC3P0Config(){
        DataSource dataSource=
                new ComboPooledDataSource("hello");
        Connection connection= null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(connection);
    }
    //使用c3p0连接
    @Test
    public void testC3P0() throws Exception {
        ComboPooledDataSource cpds=new ComboPooledDataSource();
        cpds.setUser("root");
        cpds.setPassword("123456");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        Connection connection=cpds.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值