0
点赞
收藏
分享

微信扫一扫

MySQL——JDBC工具类

拾光的Shelly 2022-01-22 阅读 84

特点

  • 线程安全
  • 分离配置
  • 手动事务

API

获取新连接

getConn();

提交并关闭流

commitAndClose(Connection conn, Statement... stmt);

回滚并关闭流

rollbackAndClose(Connection conn, Statement... stmt);

全部代码

public class JDBCUtil {
	private static ThreadLocal<Connection> local = new ThreadLocal<>();

	//获取连接
	public static Connection getConn() {
		Connection conn1 = local.get();
		if (conn1 == null) {
			Connection conn2 = newConnection();
			local.set(conn2);
			start(conn2);
			return conn2;
		} else {
			return conn1;
		}
	}

	//新连接
	private static Connection newConnection() {
		try {
			//获取配置文件信息
			Properties info = new Properties();
			InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
			info.load(is);
			String driver = info.getProperty("driver");
			String url = info.getProperty("url");
			String user = info.getProperty("user");
			String password = info.getProperty("password");
			//获取驱动,连接
			Class.forName(driver);
			return DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			throw new RuntimeException("获取连接失败");
		}
	}

	//关闭连接,执行器
	private static void close(Connection conn, Statement... stmt) {
		try {
			for (int i = 0; i < stmt.length; i++) {
				if (stmt[i] != null) {
					stmt[i].close();
				}
			}
			if (conn != null) {
				conn.close();
				local.remove();
			}
		} catch (Exception e) {
			throw new RuntimeException("关闭异常");
		}
	}

	private static void start(Connection conn) {
		try {
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			throw new RuntimeException("事务异常");
		}
	}

	public static void commitAndClose(Connection conn, Statement... stmt) {
		try {
			getConn().commit();
			close(conn, stmt);
		} catch (SQLException e) {
			throw new RuntimeException("事务异常");
		}
	}

	public static void rollbackAndClose(Connection conn, Statement... stmt) {
		try {
			getConn().rollback();
			close(conn, stmt);
		} catch (SQLException e) {
			throw new RuntimeException("事务异常");
		}
	}
}

测试

pom

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>

resources下db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxx
user=xxx
password=xxx

测试类

@Test
public void fun1() throws SQLException {
	Connection conn = JDBCUtil.getConn();
	PreparedStatement ps = null;
	String sql = "update student set sage=sage+1 where sid=1";
	try {
		ps = conn.prepareStatement(sql);
		Integer update = ps.executeUpdate();
		//Integer error=1/0;
		ps = conn.prepareStatement(sql);
		Integer update2 = ps.executeUpdate();
		/**/
		JDBCUtil.commitAndClose(conn, ps);
	} catch (SQLException e) {
		e.printStackTrace();
		JDBCUtil.rollbackAndClose(conn, ps);
	}
}

运行结果:
在这里插入图片描述
在这里插入图片描述
手动产生异常,运行结果:
在这里插入图片描述
在这里插入图片描述
成功!

举报

相关推荐

0 条评论