- Java 编程示例
- 示例 - 首页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用资源
- Java - 快速指南
- Java - 有用资源
在 Java 中如何创建保存点 & 回滚
问题描述
如何在 Java 中创建保存点和进行回滚?
解决方案
下列示例使用连接的回滚方法来回滚到先前保存的保存点。
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection(
"jdbc:derby://:1527/testDb","name","pass");
Statement stmt = con.createStatement();
String query1 = "insert into emp values(5,'name','job')";
String query2 = "select * from emp";
con.setAutoCommit(false);
Savepoint spt1 = con.setSavepoint("svpt1");
stmt.execute(query1);
ResultSet rs = stmt.executeQuery(query2);
int no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("rows before rollback statement = " + no_of_rows);
con.rollback(spt1);
con.commit();
no_of_rows = 0;
rs = stmt.executeQuery(query2);
while (rs.next()) {
no_of_rows++;
}
System.out.println("rows after rollback statement = " + no_of_rows);
}
}
结果
以上代码示例将产生以下结果。结果可能有所差异。
rows before rollback statement = 4 rows after rollback statement = 3
java_jdbc.htm
广告