javaEE JDBC, 连接数据库的工具类, 支持事务, ThreadLocal

MySql驱动(jar包)下载:https://pan.baidu.com/s/19BYnGbO3l5MOOic5K4Ooaw  密码:mwoh

第三方插件(commons-dbutils)下载:https://pan.baidu.com/s/17cyAXHZLgiayx5Y_VHvawQ  密码:6om2

c3p0连接池下载(jar包,和xml配置文件): https://pan.baidu.com/s/18DodkCHFi07MQdTGACQU7Q   密码:m6fq


DataSourceUtils.java(连接数据库的工具类,支持事务):

package com.xxx.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

	private static DataSource dataSource = new ComboPooledDataSource();

	// ThreadLocal就是一个map,键默认就是线程名不能改。 为不同的线程维护各自独立的Connection对象,同一个线程同一个Connection
	// 同一个Connection就可以实现事务的控制。
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	// 获取一个连接池
	public static DataSource getDataSource() {
		return dataSource;
	}
	
	// 从连接池中获取一个连接 (该连接不能直接用于事务的控制)
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}

	// 获取当前线程的连接对象。 (ThreadLocal可以保证线程用的是同一个Connection,就可以进行事务的控制)  
	// (事务是由连接Connection对象来控制、实现的)
	public static Connection getCurrentConnection() throws SQLException {
		Connection con = tl.get();
		if (con == null) {
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}

	// 开启事务
	public static void startTransaction() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.setAutoCommit(false);
		}
	}

	// 事务回滚
	public static void rollback() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.rollback();
		}
	}

	// 提交并且关闭资源及从ThreadLocall中释放
	public static void commitAndRelease() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.commit(); // 事务提交
			con.close(); // 关闭资源
			tl.remove(); // 从线程绑定中移除
		}
	}

	// 关闭资源方法
	public static void closeConnection() throws SQLException {
		Connection con = getCurrentConnection();
		if (con != null) {
			con.close();
		}
	}

	public static void closeStatement(Statement st) throws SQLException {
		if (st != null) {
			st.close();
		}
	}

	public static void closeResultSet(ResultSet rs) throws SQLException {
		if (rs != null) {
			rs.close();
		}
	}

}
c3p0-config.xml(c3p0连接池配置文件):
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="user">root</property>
		<property name="password">123</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql:///数据库名</property>
	</default-config> 
</c3p0-config> 


猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80890793