JDBC手动事务提交回滚的常见写法一直是rollback写在commit的catch之后:
try{
conn.setAutoCommit(false);
ps.executeUpdate(); ps.executeUpdate(); conn.commit(); }catch(Exception e){
conn.rollback();
}
但是,这种回滚是没有意义的:
一旦commit前出错, 就不提交了, 回滚无用
一旦commit了, 说明没错, 不用回滚
找到一篇和我观点相同的文章:
我以为无需回滚,即使真要回滚,需要将commit写在主要业务的try...catch之后,一旦主要业务中途出错,回滚.
表:JDBC事务3种写法回滚比较
import java.sql.*; public class TestJDBC { public static final String URL = "jdbc:mysql://127.0.0.1/test";
public static final String USER_NAME = "root";
public static final String USER_PWD = "root"; private static Connection conn = null;
private static PreparedStatement ps; private static void connOpen() throws SQLException {
conn = DriverManager.getConnection(URL, USER_NAME, USER_PWD);
} private static void connClose() throws SQLException {
if (ps != null) {
ps.close();
ps = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} private static void testRollBack() throws SQLException {
connOpen();
try { conn.setAutoCommit(false); String strSQL = "INSERT INTO customer(uname,pwd) VALUES(?,'1')";
ps = conn.prepareStatement(strSQL); // 插入一条数据
ps.setString(1, "悟空");
ps.executeUpdate(); // 出异常
if (true) {
throw new SQLException();
} // 再插入一条数据
ps.setString(1, "八戒");
ps.executeUpdate(); // conn.commit();
} catch (Exception e) {
System.out.println("异常!");
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
connClose(); } private static void selectAll() throws SQLException {
connOpen();
ps = conn.prepareStatement("select * from customer");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.print(rs.getString(2) + " : ");
System.out.println(rs.getString(1));
}
connClose();
} public static void main(String[] args) throws SQLException {
testRollBack();
selectAll();
}
}