JDBC: Transactions

A transaction is a set of actions to be carried out as a single, atomic action. Either all of the actions are carried out, or none of them are.

The classic example of when transactions are necessary is the example of bank accounts. You need to transfer $100 from one account to the other. You do so by subtracting $100 from the first account, and adding $100 to the second account. If this process fails after you have subtracted the $100 fromt the first bank account, the $100 are never added to the second bank account. The money is lost in cyber space.

To solve this problem the subtraction and addition of the $100 are grouped into a transaction. If the subtraction succeeds, but the addition fails, you can "rollback" the fist subtraction. That way the database is left in the same state as before the subtraction was executed.

You start a transaction by this invocation:

connection.setAutoCommit(false);

Now you can continue to perform database queries and updates. All these actions are part of the transaction.

If any action attempted within the transaction fails, you should rollback the transaction. This is done like this:

connection.rollback();

If all actions succeed, you should commit the transaction. Committing the transaction makes the actions permanent in the database. Once committed, there is no going back. Committing the transaction is done like this:

connection.commit();

Of course you need a bit of try-catch-finally around these actions. Here is a an example:

Connection connection = ...
try{
    connection.setAutoCommit(false);

    // create and execute statements etc.

    connection.commit();
} catch(Exception e) {
    connection.rollback();
} finally {
    if(connection != null) {
        connection.close();
    }
}

Here is a full example:

Connection connection = ...
try{
    connection.setAutoCommit(false);

    Statement statement1 = null;
    try{
        statement1 = connection.createStatement();
        statement1.executeUpdate(
            "update people set name=‘John‘ where id=123");
    } finally {
        if(statement1 != null) {
            statement1.close();
        }
    }

    Statement statement2 = null;
    try{
        statement2 = connection.createStatement();
        statement2.executeUpdate(
            "update people set name=‘Gary‘ where id=456");
    } finally {
        if(statement2 != null) {
            statement2.close();
        }
    }

    connection.commit();
} catch(Exception e) {
    connection.rollback();
} finally {
    if(connection != null) {
        connection.close();
    }
}
时间: 2024-12-12 03:48:27

JDBC: Transactions的相关文章

JDBC Transaction Management Example---reference

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 th

JDBC:JAVA & Oracle

JDBC:JAVA & Oracle 本文中未加标注的资源均来自于PolyU数据库课程的实验材料.仅作为学习使用,如有侵权,请联系删除 JDBC是什么 我之前写过一篇关于数据库和JAVA的博文,这里直接贴上相关的内容: Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法. JDBC也是Sun Microsystems的商标. JDBC是面向关系型数据库的

java.lang.IllegalStateException: Failed to load ApplicationContext

1.错误描述 INFO:2015-02-05 22:14:21[main] - Loading XML bean definitions from class path resource [applicationContext.xml] INFO:2015-02-05 22:14:22[main] - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning INFO:2015-02-05

hibernate.properties

###################### ### Query Language ### ###################### ## define query language constants / function names hibernate.query.substitutions yes 'Y', no 'N' ## select the classic query parser #hibernate.query.factory_class org.hibernate.hql

hibernate----1-1-----两表关联属性放在另一个表里面

package com.ij34.dao; import javax.persistence.*; @Entity @Table(name="Address_inf") public class Address{ @Id @Column(name="address_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private int addressId; private String message;

Hibernate常见异常

1.数据库编码问题 主要错误信息 WARN: SQL Error: 1366, SQLState: 22001 ... ERROR: Data truncation: Incorrect string value: '\xE5\xB9\xBF\xE5\xB7\x9E...' for column 'addressDetail' at row 1 详细错误 1 Jan 16, 2017 9:40:30 AM org.hibernate.annotations.common.reflection.j

1. Hibernate Map集合映射属性,创建表失败或表不存在

八月 22, 2014 8:02:39 下午 org.hibernate.annotations.common.Version <clinit>INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}八月 22, 2014 8:02:39 下午 org.hibernate.Version logVersionINFO: HHH000412: Hibernate Core {4.2.15.Final}八月 22, 2014 8:

Spring集成hibernate错误

八月 25, 2016 7:55:31 下午 org.apache.tomcat.util.digester.SetPropertiesRule begin警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:struts3_wsdc_cdgl' did not find a matching property.八月

(04)Hibernate的配置

1.Hibernate.cfg.xml 主配置 Hibernate.cfg.xml是主配置文件,其中配置大体分为3部分:数据库连接信息.其他参数.映射信息! <!DOCTYPE hibernate-configuration PUBLIC         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"         "http://www.hibernate.org/dtd/hibernate-configurat