回滚不起作用

时间:2013-07-12 07:51:37

标签: java mysql transactions

我希望回滚在发生异常时已将所有记录插入到表中。

conInsert.rollback()不起作用。

也许我错过了一些代码?

这是我的代码

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(connectionUrl);
            //con.setAutoCommit(false);
            Statement st = con.createStatement();

            String querySelectOrderInTp = "SELECT order_in_tp_id, order_in_tp_qty, order_in_tp_price, order_in_tp_article_tc_id, order_in_tp_warehouse_tc_id, inv_stock_tp_id, inv_stock_tp_qty_available from order_in_tp LEFT JOIN inv_stock_tp on(order_in_tp_warehouse_tc_id=inv_stock_tp_whouse_current_id AND order_in_tp_article_tc_id=inv_stock_tp_article_tc_id AND order_in_tp_price=inv_stock_tp_price) where order_in_tp_pick_up_timestamp = 'A' AND order_in_tp_date = '2013-06-11' GROUP BY order_in_tp_id;";
            ResultSet rs = st.executeQuery(querySelectOrderInTp);

            String queryUpdateInvStockTp = "INSERT INTO inv_stock_tp (cre_tms,upd_tms,cre_usr,upd_usr,version,usr_act,inv_stock_tp_id,inv_stock_tp_key, inv_stock_tp_whouse_current_id,inv_stock_tp_article_tc_id,inv_stock_tp_qty_available,inv_stock_tp_qty_min,inv_stock_tp_price) VALUES (NOW(),NOW(),'demo2','demo2',1,'A',null,'AAAA',?,?,?,0,2000.0000)";
            conInsert = DriverManager.getConnection(connectionUrl);
            conInsert.setAutoCommit(false);
            ps = conInsert.prepareStatement(queryUpdateInvStockTp);

            String queryUpdateOrderInTp = "UPDATE order_in_tp set order_in_tp_pick_up_timestamp = ? WHERE order_in_tp_id = ?";
            psUpdate = con.prepareStatement(queryUpdateOrderInTp);

            while(rs.next()) {
                Integer qty = rs.getInt(7) - rs.getInt(2);

                ps.setString(1, rs.getString(5));
                ps.setString(2, rs.getString(4));
                ps.setString(3, rs.getString(2));
                ps.execute();

                psUpdate.setString(1, "A");
                psUpdate.setString(2, rs.getString(1));
                psUpdate.execute();
                ps.clearParameters();
                psUpdate.clearParameters();
            }
            conInsert.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (conInsert != null) {
                try {
                    System.err.print("Transaction is being rolled back");
                    conInsert.rollback();
                } catch (SQLException excep) {
                    excep.printStackTrace();
                }
            }
        }

我在最后一条记录中做了一个例外,但它之前的所有记录仍然被插入。

1 个答案:

答案 0 :(得分:0)

默认情况下,MySQL在启用自动提交模式的情况下运行。这意味着只要执行更新(修改)表的语句,MySQL就会将更新存储在磁盘上以使其永久化。我不懂java,但要确保你有START TRANSACTION语句,然后是COMMIT或ROLLBACK。