JdbcUtils

JdbcUtils用来获取Connection对象,以及开启和关闭事务。

1、Connection getConnection():从c3p0连接池获取Connection对象,所以需要提供c3p0-config.xml配置文件;

2、 beginTransaction():为当前线程开启事务;

3、commitTransaction():提交当前线程的事务;

4、 rollbackTransaction():回滚当前线程的事务;

5、 releaseConnection(Connection):如果参数连接对象不是当前事务的连接对象,那么关闭它,否则什么都不做;

package cn.edu.zk.sxx.test;

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

import junit.framework.Assert;

import org.junit.Test;

import cn.itcast.jdbc.JdbcUtils;

/**
 * 测试JdbcUtils类
 * JdbcUtils用来获取Connection 底层使用了c3p0连接池!(需要提供c3p0配置文件) 还需要mysql驱动
 * 
 * @author 
 * 
 */
public class jdbcUtilsTest {
    @Test
    public void testGetConnection() throws SQLException {
        Connection con = JdbcUtils.getConnection();// 获取连接
        System.out.println(con);
        JdbcUtils.releaseConnection(con);
        System.out.println(con.isClosed());// 查看是否关闭
    }

    /**
     * 当开始事务后,调用getConnection()会为当前线程创建Connection,
     * 而且多次调用getConnection()返回的是同一个对象
     * 
     * @throws SQLException
     */
    @Test
    public void testTansaction()  {
        try {
            JdbcUtils.beginTransaction();// 开启事务
            //第一次获取当前线程的事务连接对象
            Connection c1 = JdbcUtils.getConnection();
                    
            //第二次获取当前线程的事务连接对象
            Connection c2 = JdbcUtils.getConnection();
            
            //提交事务
            JdbcUtils.commitTransaction();
        } catch (Exception e) {
            try {
                JdbcUtils.rollbackTransaction();//回滚事件
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        
        
    }
}

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config> 
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">123</property>
        
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>
 
原文地址:https://www.cnblogs.com/suxiaoxia/p/6832063.html