---
title: "jdbc中利用Savepoint实现rollback"
author: "java_frog"
date: "2011-10-20T14:49:52Z"
tags: []
categories: ["编程语言"]
slug: "jdbc-savepoint-rollback"
draft: false
lastmod: "2011-10-20T14:49:52Z"
id: 1203160
url: "https://java-frog.iteye.com/blog/1203160"
---

首先我们来说一下setAutoCommit，当我们设置为true或默认情况下，jdbc事务会自动提交，当我们将setAutoCommit设为false时，虽然是手动提交事务，但是如果不写手动提交代码，最后也会提交。那有什么不一样呢，例如：我们在一个方法内多次执行数据库操作，中间有根据状态或上一返回值来确定是否回滚的情况下，如果是自动提交，那回滚就不起作用，如果是手动提交状态，那回滚就有效。

接下来还是看Savepoint

```java

con.setAutoCommit(false);
			Savepoint first=con.setSavepoint("first");
			ps=con.prepareStatement("update  employees t set t.first_name='guohr1' where t.employee_id=207");
			flag=ps.executeUpdate();
			log.info("flag:"+flag);
			
			Savepoint second=con.setSavepoint("second");
			ps=con.prepareStatement("update  employees t set t.first_name='guohr2' where t.employee_id=207");
			flag=ps.executeUpdate();
			log.info("flag:"+flag);
			
			Savepoint third=con.setSavepoint("third");
			ps=con.prepareStatement("update  employees t set t.first_name='guohr3' where t.employee_id=207");
			flag=ps.executeUpdate();
			log.info("flag:"+flag);
			
			con.rollback(second);

```

    我在每次update前创建了一个回滚点，当最后rollback的时候如果参数如上为second,那么first_name='guohr1'，如果参数为third,那么为guohr2，当然实际中不是像滚雪球一样这么随意滚的，可以根据前面返回的状态或值来判断是否需要回滚及滚到哪一步之前。