【发布时间】:2019-11-19 08:14:50
【问题描述】:
我有代码:
@Override
public void update(Duck entity) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(daoProperties.getUrl(), daoProperties.getUser(), daoProperties.getPassword());
connection.setAutoCommit(false);
connection.commit()
preparedStatement = connection.prepareStatement(INSERT_FROG);
preparedStatement.setInt(ID, entity.getFrogId());
preparedStatement.setString(NAME, entity.getMyFrogFriend().name());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
try {
PreparedStatement duckPreparedStatement = connection.prepareStatement(INSERT_DUCK);
duckPreparedStatement.setInt(ID, entity.id());
//..
duckPreparedStatement.executeUpdate();
// throw new SQLException();
// connection.commit();
} catch (SQLException e) {
log.warning("error with statements or connection");
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
我希望,如果第二次插入失败,那么我们不进行第一次插入。但是这段代码不起作用,如果我们要删除第一个评论,第一次插入就会完成。我做错了什么?
【问题讨论】:
-
connection.commit()到底应该是NO吗? -
为什么你在做任何事情之前都要做
connection.commit()? -
@YCF_L 是的,我已经评论过了。如果我抛出异常,提交的行将不起作用
-
@petrov.aleksandr 使您的代码更通用,这样您就不必为相同的用例复制相同的代码,其次您应该进行事务管理,以便回滚可以帮助 SQL 操作失败
-
@ScaryWombat 因为我不知道,如果第二次插入发生了事情,我怎么能回到开头
标签: java jdbc transactions