2012-10-29 47 views
0

我有表所示:MySQL的事務刪除和Java

Table A: 
`id | name` 

Table B: 
`id | A_id | ....` 

A_id is a foreign key to Table A, the Engine is InnoDB 

這是一個失敗的代碼:

String[] cleanupQueries = new String[] { "DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name = 'test')", 
              "DELETE FROM A WHERE name = 'test'" }; 

    Connection connection; 
    try { 
     connection = DriverManager.getConnection(getConnectionString()); 
     connection.setAutoCommit(false); 
    } catch (SQLException e) { 
     throw new RuntimeException("Error establishing a database connection!"); 
    } 

    try { 
     for(String cleanupQuery : cleanupQueries) { 
      PreparedStatement statement = connection.prepareStatement(cleanupQuery); 
      statement.executeUpdate(); //FAILS WHEN EXECUTING THE SECOND QUERY 
     } 
    } catch(SQLException e) { 
     throw new RuntimeException("Error while executing the queries in the transactional context!"); 
    } 

    try { 
     connection.commit(); 
    } catch (SQLException e) { 
     rollback(connection); 
     throw new RuntimeException("Error while comitting!"); 
    } 

的例外,我得到的是: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails ('DATABASE/TABLE', CONSTRAINT 'FK_B_A' FOREIGN KEY ('FK_A') REFERENCES 'A' ('ID') ON DEL)

的數據庫不會讓我刪除A,但仍有B的左邊,但第一個查詢刪除了所有B的。我想刪除所有的B和他們完全參考的A。

我不想更改表以進行級聯刪除。我該怎麼做才能讓代碼工作?

回答

0

原因的錯誤是

的外鍵引用了表中一個ID,所以如果你想刪除F_Key,首先你應該刪除外鍵的子引用值,那麼只有它可以刪除父母。

糾正我,如果「錯了..

+0

你是對的,但我不想這樣做事務上下文之外。 – trampi

0

只需添加刪除時,當你刪除原父條目外鍵constraint.The子表項將被自動刪除級聯是真實的。

+0

我對數據庫結構沒有影響。我需要以編程方式進行,確保交易僅在有限的情況下完成。 – trampi

0

嘗試:

"DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name IN 'test')" 
+0

感謝您的幫助,但沒有解決它。 – trampi