我有一个升级DB的方法:
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。有什么建议吗?
答案 0 :(得分:2)
MySQL / InnoDB不支持此功能。所有DDL语句(CREATE TABLE
,ALTER TABLE
,CREATE INDEX
,DROP ...
)总是在事务控制之外发生。
这是IIRC Postgres可以更好地处理的弱点,但是对于MySQL,你必须通过在回滚的情况下自行恢复更改来解决这个问题。