首页 > 数据库技术 > 详细

JDBC - Transaction

时间:2017-09-05 23:44:36      阅读:302      评论:0      收藏:0      [点我收藏+]

Transaction: a bunch of operation in logic, the unit which consists the operation will works all or breaks down all. 

Every operation of MySQL server is a independent transaction in default situation.

TPL(Transaction Processing Language):

  start transaction

  commit

  rollback

SQL statement:

 

CREATE TABLE account(
   id INT PRIMARY KEY AUTO_INCREMENT,
   name VARCHAR(40),
   money FLOAT   
);
INSERT INTO account(name,money) VALUES(aa,1000);
INSERT INTO account(name,money) VALUES(aa,1000);
INSERT INTO account(name,money) VALUES(aa,1000);

START TRANSACTION;
UPDATE account SET money=money-100 WHERE name=aa;
UPDATE account SET money=money+100 WHERE name=bb;
COMMIT;

 

 JDBC code:

package com.pp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.pp.util.JdbcUtil;

public class TransactionDemo {
    @Test
    public void test1() {
        Connection connection = null;
        PreparedStatement pstatement = null;
        try {
            connection = JdbcUtil.getConnection();
            // start transaction
            connection.setAutoCommit(false);
            pstatement = connection
                    .prepareStatement("UPDATE accout SET money=money-100 WHERE name=‘aa‘");
            pstatement.executeUpdate();
            pstatement = connection
                    .prepareStatement("UPDATE accout SET money=money-100 WHERE name=‘aa‘");
            pstatement.executeUpdate();
            // commit
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
}

 

JDBC - Transaction

原文:http://www.cnblogs.com/ppcoder/p/7482476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!