2012-04-05 64 views
0

我有做一個簡單的mysql插入,當我試圖回滾插入操作如下,在一個錯誤,但它不是在錯誤rollingback的方法,請協助我的工作,回滾不會在Java中

public void addFamer(FamerDTO famer) throws Exception { 
     Connection con = JDBCConnectionPool.getInstance().checkOut(); 
     con.setAutoCommit(false); 

     try { 


      String generalFamerDataSQL = "INSERT INTO famers(famer_code, name_wt_initials, full_name, gender, " 
        + "nic_or_passport_no, sc_possition, phone_home, phone_mobile, phone_office) VALUES(?,?,?,?,?,?,?,?,?)"; 
      PreparedStatement insertFamerPS = con.prepareStatement(generalFamerDataSQL, PreparedStatement.RETURN_GENERATED_KEYS); 
      insertFamerPS.setString(1, famer.getFamerCode()); 
      insertFamerPS.setString(2, famer.getNameWithInitials()); 
      insertFamerPS.setString(3, famer.getNameInFull()); 
      insertFamerPS.setString(4, famer.getGender()); 
      insertFamerPS.setString(5, famer.getNICorPassportNo()); 
      insertFamerPS.setString(6, famer.getSocietyPosission()); 
      insertFamerPS.setString(7, famer.getHomePhone()); 
      insertFamerPS.setString(8, famer.getMobilePhone()); 
      insertFamerPS.setString(9, famer.getOfficePhone()); 
      insertFamerPS.execute(); 


String famerRelations = "INSERT INTO org_reg_blk_soc_fmr(org_id, region_id, famer_id, block_id, soc_id) " 
        + "VALUES (?,?,?,?,?)"; 
      PreparedStatement famerRelationsPS = con.prepareStatement(famerRelations); 
      famerRelationsPS.setInt(1, famer.getOrganization().getOrg_id()); 
      famerRelationsPS.setInt(2, famer.getRegion().getRegion_id()); 
      famerRelationsPS.setInt(3, famerID); 
      famerRelationsPS.setInt(4, famer.getBlock().getBlockId()); 
      famerRelationsPS.setInt(6, famer.getSociety().getSoc_id()); //intentionally made an error here to test, put index as 6 for 5 
      famerRelationsPS.execute(); 


      con.commit(); 
     } catch (Exception e) { 
      if (con != null) { 
       logger.info("Rolling back!"); 
       con.rollback();      
      } 
      logger.error(e.getLocalizedMessage()); 

     } finally { 
      con.setAutoCommit(true); 
      JDBCConnectionPool.getInstance().checkIn(con); 
     } 

    } 

一旦使用所需的參數調用此方法,因爲第二個插入語句中存在錯誤,我期望回滾第一個插入操作。但認爲顯示了錯誤,則通過第一個插入語句向數據庫添加一條記錄。

+0

您是否嘗試過在插入前明確啓動新的事務? – 2012-04-05 09:42:44

回答

7

只需檢查 - 您使用的表格類型是什麼?上次我使用MySQL時,MyISAM表不支持事務,這意味着您必須使用另一個表類型,例如InnoDB的。

+0

(刪除-1),因爲它是第一個問/看。 – 2012-04-05 09:41:22

+0

感謝Rory,我的mysql表是MyISAM,所以我將它們改爲innodb,然後工作。 – Harsha 2012-04-05 09:45:56

+0

@哈沙你應該考慮接受這個答案,如果它解決了你的問題:) – Jim 2012-04-05 10:26:15