In this post, we want to talk about JDBC Transactions and how we can manage the operations in a database.

The most popular DBMS like MySQL and Oracle have by default the option autocommit enabled, it means immediately after any DML Operation saves the changes and makes them visible to all users. To use transactions must set the databse parameter autocommit to false.

The management of the database using transaction allows us to maintain consistency in the data, according to his ‘ACID’ property.

Transaction Properties

What we want with Transactions? To Maintain this four properties:

  • Atomicity, it’s simple either all operations in database occur, or nothing occurs.
  • Consistency, ensures that the database is in a valid state before and after the transaction.
  • Isolation, any transaction is independent of another, and your result doesn’t depends of any other.
  • Durability, the result of commit a transaction must persist in a non-volatile memory even if occurs a crash or power loss.

Tools

For this example we use:

  1. JDK 1.7.0_67 (rt.jar includes java.sql package)
  2. Mysql-connector-java 5.1.34
  3. Eclipse Luna
  4. MySQL Community Server 5.6.22

1. Example:

DBConnection.java:

01 package com.javacodegeeks.jdbc.transactions;
02  
03 import java.sql.Connection;
04 import java.sql.DriverManager;
05 import java.sql.SQLException;
06  
07 /**
08  * @author Andres.Cespedes
09  *
10  */
11 public class DBConnection {
12  
13     private static String DB_URL = "jdbc:mysql://localhost:3307/test";
14     private static String DB_USER = "admin";
15     private static String DB_PASSWORD = "admin";
16  
17     public static Connection getConnection() throws SQLException {
18         Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
19         return connection;
20     }
21 }

We use DBConnection only to get the connection, any other operation is handled in the main class.

DBTransaction.java:

01 package com.javacodegeeks.jdbc.transactions;
02  
03 import java.sql.Connection;
04 import java.sql.PreparedStatement;
05 import java.sql.SQLException;
06  
07 /**
08  * @author Andres.Cespedes
09  *
10  */
11 public class DBTransaction {
12  
13     private static String INSERT = "INSERT INTO test.department (idDepartment, name) VALUES (?, ?)";
14  
15     /**
16      * @param args
17      */
18     public static void main(String[] args) {
19         Connection connection = null;
20         PreparedStatement pstmt = null;
21         PreparedStatement pstmt2 = null;
22         try {
23             connection = DBConnection.getConnection();
24         catch (SQLException e) {
25             System.err.println("There was an error getting the connection");
26         }
27         try {
28             connection.setAutoCommit(false);
29             System.err.println("The autocommit was disabled!");
30         catch (SQLException e) {
31             System.err.println("There was an error disabling autocommit");
32         }
33         // Starts JDBC Transaction
34         try {
35             pstmt = connection.prepareStatement(INSERT);
36             pstmt2 = connection.prepareStatement(INSERT);
37              
38             pstmt.setInt(11);
39             pstmt.setString(2"Madrid");
40             pstmt.execute();
41              
42             pstmt2.setInt(12);
43             pstmt2.setString(2"Galicia");
44             pstmt2.execute();
45              
46             connection.commit();
47             System.err.println("The transaction was successfully executed");
48         catch (SQLException e) {
49             try {
50                 //We rollback the transaction, atomicity!
51                 connection.rollback();
52                 System.err.println(e.getMessage());
53                 System.err.println("The transaction was rollback");
54             catch (SQLException e1) {
55                 System.err.println("There was an error making a rollback");
56             }
57         }
58     }
59 }

The connection.commit() applies all the changes before him. The key is to disable the autocommit and to group the sentences to to manage them in a transaction with a final commit.

We try to execute the transaction and this was the result.

1 The connection is successfully obtained
2 The autocommit was disabled!
3 The transaction was successfully executed

Here we should note that if one of the operations does not run correctly, all entries aren’t made and the database remains unchanged.

DBSavePoint.java:

01 package com.javacodegeeks.jdbc.transactions;
02  
03 import java.sql.Connection;
04 import java.sql.PreparedStatement;
05 import java.sql.SQLException;
06 import java.sql.Savepoint;
07  
08 /**
09  * @author Andres.Cespedes
10  *
11  */
12 public class DBSavePoint {
13  
14     private static String INSERT = "INSERT INTO test.department (idDepartment, name) VALUES (?, ?)";
15  
16     public static void insertRow(Connection conn, int idRow, String contentRow)
17             throws SQLException {
18         PreparedStatement pstmt = null;
19         pstmt = conn.prepareStatement(INSERT);
20         pstmt.setInt(1, idRow);
21         pstmt.setString(2, contentRow);
22         pstmt.execute();
23         pstmt.close();
24     }
25  
26     /**
27      * @param args
28      */
29     public static void main(String[] args) {
30         Connection connection = null;
31         Savepoint savepoint = null;
32         try {
33             connection = DBConnection.getConnection();
34         catch (SQLException e) {
35             System.err.println("There was an error getting the connection");
36         }
37         try {
38             connection.setAutoCommit(false);
39             System.err.println("The autocommit was disabled!");
40         catch (SQLException e) {
41             System.err.println("There was an error disabling autocommit");
42         }
43         // Starts JDBC Transaction
44         try {
45             insertRow(connection, 1"Madrid");
46             insertRow(connection, 2"Eibar");
47             savepoint = connection.setSavepoint("SavePoint1");
48             insertRow(connection, 3"Galicia");
49  
50             connection.commit();
51             System.err.println("The transaction was successfully executed");
52         catch (SQLException e) {
53             try {
54                 // We rollback the transaction, to the last SavePoint!
55                 connection.rollback(savepoint);
56                 System.err.println(e.getMessage());
57                 System.err
58                         .println("The transaction was rollback to the last savepoint");
59             catch (SQLException e1) {
60                 System.err.println("There was an error making a rollback");
61             }
62         }
63     }
64  
65 }

The method setSavepoint of class Connection allows to create a checkpoint internally in the transaction, and if a error occurs we can back to the savepoint with all of changes made before.

2. Summary

Here we tried to understand how to manage the JDBC Operations through transactions and how to make check points by means ofSavePoint class.

http://examples.javacodegeeks.com/core-java/sql/jdbc-transaction-management-example/

JDBC Transaction Management Example---reference的更多相关文章

  1. spring Transaction Management --官方

    原文链接:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html 12.  ...

  2. Spring.NET的中间数据层(Middle Tier Data Access)——事务管理(Transaction management)

    简介 Spring.NET为事务管理提供了一个持久化抽象(consistent abstraction ),其优点如下: 为不同事务API,例如ADO.NET,Enterprise Services, ...

  3. Could not roll back JDBC transaction途径

    [异常]接口数量:DM02;错误代码:ERR_EAI_02_014; 错误叙述性说明:当将中间库异常Could not roll back JDBC transaction; nested excep ...

  4. Java Transaction Management

    Just a few weeks ago, I had a discussion with one of my colleagues about how to manage the transacti ...

  5. Cisco IOS basic system management command reference

    absolute : to specify an absolute time for a time-range (in time-range configuration mode) no absolu ...

  6. JDBC Tutorials: Commit or Rollback transaction in finally block

    http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...

  7. Spring Boot Reference Guide

    Spring Boot Reference Guide Authors Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch,  ...

  8. 翻译:Spring-Framework-Reference Document:11-Transaction Management

    TUESDAY, 07 APRIL Comprehensive transaction support is the most compelling reasons to use the Spring ...

  9. CSDN上看到的一篇有关Spring JDBC事务管理的文章(内容比较全) (转)

    JDBC事务管理 Spring提供编程式的事务管理(Programmatic transaction manage- ment)与声明式的事务管理(Declarative transaction ma ...

随机推荐

  1. java通过jni方式获取硬盘序列号(windows,linux)

    linux系统java通过jni方式获取硬盘序列号 http://blog.csdn.net/starter110/article/details/8186788 使用jni在windows下读取硬盘 ...

  2. jQuery实现iframe的自适应高度

    假设我们在当前页面要嵌套一个iframe 1 <iframe id="myframe" src="test.html" height="240& ...

  3. 关于Matlab作图的若干问题

          看到了北京一则新闻,想到如何测试双向镜子?百度之.              只要做以下简单的测试:把你的指甲尖放在镜子表面,如果在指甲尖与倒映图像之间有间隙,那就是真的镜子.然而,如果你 ...

  4. SDUT 2352 Run Length Encoding

    点我看题目 题意 :将给定的字符串编码,编码的规则根据两条,1.如果字符串里有连续相等的字符,就变为两个字符,一个是这些连续相同的字符的个数,另一个是这个字符,但是如果数量超过了9个,那就输出9再输出 ...

  5. android Mediaplayer硬件解码浅探

    在讨论stagefright如何调用硬件解码之前,我们要先清楚几个问题. 我不展开这几个结论是如何得来的,因为这部分属于进程间通信binder的理解,和多媒体本身无关. 一.问题空间 这个有点像方法学 ...

  6. Ubuntu下安装Qt4.5(包括X86和ARM版本)

    条件:TQ2440开发板,虚拟机安装的Ubuntu10.04,安装好天嵌自带的GCC交叉编译器参考:http://blog.csdn.net/newnewman80/article/details/6 ...

  7. Qt 子窗口内嵌到父窗口中(无边框附体show即可)good

    有时需要把一个子窗口内嵌进入父窗口当中. 我们可以这样做 1.新建一个QWidget 或者QDialog的子类 ClassA(父类为ClassB) 2.在新建类的构造函数中添加设置窗口属性 setWi ...

  8. eclipse或IDEA连接魅蓝

    1.首先 安装ADB 驱动 http://developer.android.com/tools/device.html 如果没装就自行去下载安装 别的品牌都可以顺利连接,魅族手机特有的原因导至在开发 ...

  9. windwos server 2008下iis7各种操作

    1.发布一个asp程序带access数据库的 默认server 08是安装了iis7的,但是它默认没支持asp这项,这时你可以直接去控制面板--程序和功能--打开或关闭windows功能(双击打开)- ...

  10. linux IPC总结——管道

    管道 管道是unix ipc的最古老形式,是一种在内存中的特殊文件,只能在具有公共祖先的进程之间使用(即父子进程,兄弟进程). 管道由pipe函数创建 #include <unistd.h> ...