Mysql事务例子

事务:

最小的逻辑单位,内部有多个操作,如果一个失败,全部都失败。意思就是同步一致,事务内部的全部条件都成立,该事务才成立,是且条件

注意:
connection = jdbcUtil.getConnection(); 默认开启时自动提交
要设置成:
connection.setAutoCommit(false);

基本格式:

try {
        connection = jdbcUtil.getConnection();
        connection.setAutoCommit(false);    
    } catch (SQLException e) {
        //出现异常,需要回滚事务
        connection.rollback();
    }finally {
        //所有的操作执行成功, 提交事务
        connection.commit();
        jdbcUtil.close(connection, preparedStatement);
    }

全部回滚:

public static void main(String[] args) throws SQLException{
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        Savepoint savepoint = null;
        String sql1="INSERT INTO teacher(name) value('1')";
        String sql2="INSERT INTO teacher(name) value('2')";
        try {
            connection = jdbcUtil.getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();
            PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
            preparedStatement2.executeUpdate();


        } catch (SQLException e) {
            //出现异常,需要回滚事务
            connection.rollback();
        }finally {
            //所有的操作执行成功, 提交事务
            connection.commit();
            jdbcUtil.close(connection, preparedStatement);
        }

    }

如果不想全部回滚怎么办?

部分回滚:

public static void main(String[] args) throws SQLException{
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        Savepoint savepoint = null;
        String sql1="INSERT INTO teacher(name) value('1')";
        String sql2="INSERT INTO teacher(name) value('2')";
        String sql3="INSERT INTO teacher(name) value('3')";
        String sql4="INSERT1 INTO teacher(name) value('4')";
        try {
            connection = jdbcUtil.getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();
            PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
            preparedStatement2.executeUpdate();
            savepoint = connection.setSavepoint();

            PreparedStatement preparedStatement3 = connection.prepareStatement(sql3);
            preparedStatement3.executeUpdate();
            PreparedStatement preparedStatement4 = connection.prepareStatement(sql4);
            preparedStatement4.executeUpdate();

        } catch (SQLException e) {

            connection.rollback(savepoint);
            e.printStackTrace();
        }finally {
            connection.commit();
            jdbcUtil.close(connection, preparedStatement);
        }

    }

你可能感兴趣的:(SQL,JAVA,Web基础)