jdbc文件夹下有两个类,分别是JdbcUtils类和TxQueryRunner类;
一.JdbcUtils类
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 使用本类的方法,必须提供c3p0-copnfig.xml文件
* @author qdmmy6
*/
public class JdbcUtils {
// 饿汉式
//创建c3p0数据源对象
private static DataSource ds = new ComboPooledDataSource();
/**
* 它为null表示没有事务
* 它不为null表示有事务
* 当开启事务时,需要给它赋值
* 当结束事务时,需要给它赋值为null
* 并且在开启事务时,让dao的多个方法共享这个Connection
*/
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
public static DataSource getDataSource() {
return ds;
}
/**
* dao使用本方法来获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
/*
* 如果有事务,返回当前事务的con
* 如果没有事务,通过连接池返回新的con
*/
Connection con = tl.get();//获取当前线程的事务连接
if(con != null) return con;
return ds.getConnection();
}
/**
* 开启事务
* @throws SQLException
*/
public static void beginTransaction() throws SQLException {
Connection con = tl.get();//获取当前线程的事务连接
if(con != null) throw new SQLException("已经开启了事务,不能重复开启!");
con = ds.getConnection();//给con赋值,表示开启了事务
con.setAutoCommit(false);//设置为手动提交
tl.set(con);//把当前事务连接放到tl中
}
/**
* 提交事务
* @throws SQLExcep