JDBC 事务

事务

package jdbc;

import java.sql.*;

public class TxTest {
    public static void main(String[] args) throws SQLException {
        test();
    }

    static void test() throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        Savepoint sp = null;
        try {
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);
            st = conn.createStatement();

            String sql = "update user set money=money-10 where id=1";
            st.executeUpdate(sql);
            sp = conn.setSavepoint();

            sql = "update user set money=money-10 where id=3";
            st.executeUpdate(sql);

            sql = "select money from user where id=4";
            rs = st.executeQuery(sql);

            float money = 0.0f;
            if (rs.next()) {
                money = rs.getFloat("money");
            }
            if (money > 300)
                throw new RuntimeException("已经超过最大值!");

            sql = "update user set money=money+10 where id=2";
            st.executeUpdate(sql);

            conn.commit();
        } catch (RuntimeException e) {
            if (conn != null && sp != null) {
                conn.rollback(sp);
                conn.commit();
            }
        } catch (SQLException e) {
            if (conn != null) {
                conn.rollback();
                throw e;
            }
        } finally {
            JdbcUtils.free(rs, st, conn);
        }
    }
}

 

posted @ 2019-09-26 22:55  一只桔子2233  阅读(106)  评论(0编辑  收藏  举报