在conn.rollback()上出现错误未处理的SQLException ...如何正确使用commit()?

时间:2018-05-21 00:41:47

标签: java sql transactions try-catch commit

所以,我正在努力学习。我为slopinnes道歉。这段代码依赖于事务,所以自动提交必须是假的,但是它会在conn.rollback()上抛出一个未处理的SQLException,我不明白为什么如果它已经在catch(异常)里面......我应该把所有内容都包装在另一个上的try-catch?

try {
    conn.setAutoCommit(false);

    String sql="SELECT l.toy_id FROM LETTER l WHERE toy_id=?";
    PreparedStatement selectStatement = conn.prepareStatement(sql);

    String sqlD="DELETE FROM TOY WHERE toy_id=?";
    PreparedStatement deleteStatement = conn.prepareStatement(sqlD);

    String sqlU="INSERT INTO TOY (toy_id, toy_name, price,toy_type, manufacturer) VALUES (?,?,?,?,?)";
    PreparedStatement UpdateStatement = conn.prepareStatement(sqlU);

    // TODO Update or delete Toy for every row in file
    for (List<String> row : fileContents) {//!!!!!!!no borrar!!!    
        int toy_id=getToyId(row);   

        //should another try go here??
        selectStatement.setInt(1, toy_id);
        ResultSet rs = selectStatement.executeQuery(sql);
        if (!rs.first()) {//HERE WE DELETE
            deleteStatement.setInt(1, toy_id);
            deleteStatement.executeUpdate();
        }else {
          while (rs.next()) {//HERE WE UPDATE
                UpdateStatement.setInt(1, toy_id);
                UpdateStatement.executeUpdate(); 
          } 
        }       
        rs.close();     
    }
    conn.commit();  
}
catch (SQLException e){
    System.out.println("ERRRROOOOOOORRRRR");
    conn.rollback();
}   

2 个答案:

答案 0 :(得分:0)

首先尝试应该引用连接(conn.setAutoCommit(false); ...)并且内部尝试应该引用事务的语句。见Transaction rollback on SQLException using new try-with-resources block

答案 1 :(得分:0)

在最终版块中添加以下代码:

    try {  
        if (connection != null) {  
        connection.rollback();  
        connection.setAutoCommit(true);  
    }  
    } catch (SQLException e) {  
        LOG.error(e.getMessage(), e);  
    }  

注意:您可以将auto commit设置为true