2010-12-03 31 views
0

我有升級數據庫的方法:SQL批量更新 - 在「CREATE TABLE」上回滾?

private void executeUpdateBatch(String... sql) throws SQLException { 
    JdbcConnection connJbdc = new JdbcConnectionImpl(); 
    Connection conn = connJbdc.getConnection(); 
    conn.setAutoCommit(false); 
    Statement st = conn.createStatement(); 

    for(String s : sql) { 
     st.addBatch(s); 
    } 

    try { 
     // execute the batch 
     int[] updateCounts = st.executeBatch(); 
     } catch (BatchUpdateException e) { 
     int[] updateCounts = e.getUpdateCounts(); 
     checkUpdateCounts(updateCounts); 
     try { 
      conn.rollback(); 
     } catch (Exception e2) { 
     } 

     throw new SQLException(e); 
     } 
     // since there were no errors, commit 
     conn.commit(); 

     st.close(); 
     conn.close(); 
} 

和升級方法:

public void upgradeTo5() throws SQLException { 
    executeUpdateBatch("CREATE TABLE project (" 
      + "id INT(10) unsigned NOT NULL auto_increment, " 
      + "title VARCHAR(255) NOT NULL, " 
      + "date_from DATE NULL, date_to DATE NULL," 
      + "active BIT NOT NULL, PRIMARY KEY (id))", 
      "INSERT INTO project(titlea) VALUES('test1')"); 
} 

錯誤是INSERT只是爲了測試回滾。

那麼,現在的問題是它不會回滾CREATE TABLE project。表是InnoDB。有什麼建議麼?

回答

2

這不受MySQL/InnoDB支持。所有DDL語句(CREATE TABLE,ALTER TABLE,CREATE INDEX,DROP ...)總是發生在事務控制之外。

這是IIRC Postgres可以更好地處理的一個弱點,但對於MySQL,您必須通過在回滾情況下自行恢復更改來解決此問題。