当前位置:Gxlcms > 数据库问题 > JDBC - Transaction

JDBC - Transaction

时间:2021-07-01 10:21:17 帮助过:19人阅读

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

标签:tco   demo   null   opera   val   print   on()   exception   bsp   

人气教程排行