JDBC之事务及设置事务超时配置

JDBC事务过程-》开启事务setAutoCommit(false)-》事务异常回滚rollback()-》事务提交commit()

说明:本文JDBCUtils工具类在https://blog.csdn.net/qq_15076569/article/details/82191167已经附上源码

注意:在使用JDBC事务时需考虑事务超时问题,在连接mysql的url后增加connectTimeout=60000&socketTimeout=60000:

jdbc:mysql://xxx.xx.xxx.xxx:3306/database?connectTimeout=60000&socketTimeout=60000

增加Statement对象设置查询超时setQueryTimeout(毫秒)

ps.setQueryTimeout(3000);

本文模拟经典转账案例(张三转账给李四)为例:


import com.itheima.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestTransactional {
    public static void main(String[] args) {
        //张三 -->  李四 转1000块钱
        Connection conn = null;
        Statement stat = null;
        try {
            //2
            //3 获取连接对象
            conn = JDBCUtils.getConnection();
            //4
            stat = conn.createStatement();
            //5
            String sql1 = "update account set money = money - 1000 where aid=1;";
            String sql2 = "update account set money = money + 1000 where aid=2;";

            //开启事务(相当于关闭事务的自动提交功能)
            conn.setAutoCommit(false);

            int num1 = stat.executeUpdate(sql1);        //张三 - 1000
            //System.out.println(1/0);
            int num2 = stat.executeUpdate(sql2);        //李四 + 1000
            if (num1== num2 && num1==1) {
                conn.commit();      //提交事务
                System.out.println("转账成功");
            } else {
                conn.rollback();    //事务回滚
                System.out.println("转账失败");
            }
        } catch (Exception e) {
            try {
                conn.rollback();    //事务回滚
                System.out.println("转账失败");
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.release(conn,stat);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_15076569/article/details/82191512