Jdbc Connection 为什么无法执行?

2022-05-25 12:52:01 +08:00
 jimisun

测试的是一个 JDBC 事务中可能包含对多个 JDBC 事务的操作,当该事务中的任何一个方法抛出异常后所有的 JDBC 事务均回滚。本例中 update2 的 preparedStatement2.executeUpdate()却无法执行,为什么?

public class JdbcDemo21 {

    public static void main(String[] args) {


        try {//加载 MySql 的驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动程序类 ,加载驱动失败!");
            e.printStackTrace();
        }
        String url = "jdbc:mysql://1.fdsf229.fdsf:307/test";
        String dbusername = "root";
        String dbpassword = "root";
        try {
            Connection con = DriverManager.getConnection(url, dbusername, dbpassword);
            Connection con2 = DriverManager.getConnection(url, dbusername, dbpassword);
            con.setAutoCommit(false);
            con2.setAutoCommit(false);
            
            Savepoint conSavepoint = con.setSavepoint();

            update1(con);
            update2(con2, con, conSavepoint);

            con2.commit();
            con.commit();

            con.close();
            con2.close();
        } catch (SQLException se) {
            System.out.println("数据库连接失败!");
            se.printStackTrace();
        }


    }

    private static void update1(Connection con) throws SQLException {
        String sql = "update user set count = count - 100 where username = 'zhangsan'";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        int i = preparedStatement.executeUpdate();
    }

    private static void update2(Connection con, Connection connection, Savepoint conSavepoint) throws SQLException {
        try {
            String sql2 = "update user set count = count + 100 where username = 'lisi'";
            PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
            int i1 = preparedStatement2.executeUpdate();
            int errorTemp = 1 / 0;
        } catch (RuntimeException runtimeException) {
            runtimeException.printStackTrace();
            con.rollback();
            connection.rollback(conSavepoint);
        }

    }
}

513 次点击
所在节点    问与答
2 条回复
huntagain2008
2022-05-25 13:49:46 +08:00
小白以为是连接问题,话说 catch 到的 异常是什么?
jimisun
2022-05-26 08:52:12 +08:00
@huntagain2008 子方法异常控制父方法进行回滚

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/855185

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX