JDBC事务还原点使用示例

本文深入探讨了在Java中使用JDBC进行数据库操作时如何利用事务和还原点来增强数据处理的可靠性。通过示例代码,我们展示了如何设置事务,创建还原点,并在异常情况下回滚到该点,确保数据的一致性和安全性。
/**
	 * JDBC事务还原点
	 * @param user
	 * @return
	 */
	private boolean jdbcSave(User user) {
		boolean success = false;
		System.out.printf("[Thread : %s] save user :%s\n", 
				Thread.currentThread().getName(), user);
		
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
			connection.setAutoCommit(false);
			//设置还原点
			Savepoint savepoint = connection.setSavepoint();
			PreparedStatement preparedStatement = connection.prepareStatement("insert into users(name) values(?);");
			preparedStatement.setString(1, user.getName());
			success = preparedStatement.executeUpdate() > 0;
			
			try {
				transactionalSave(user);
			} catch (Exception e) {
				connection.rollback(savepoint);
			}
			//提交事务
			connection.commit();
			//释放还原点
			connection.releaseSavepoint(savepoint);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(connection != null) {
				connection.close();
			}
		}
		return false;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值