public class TestTransaction {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?user=root&password=11111111";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
//将自动提交事务设置为false
conn.setAutoCommit(false);
stmt.addBatch("update person set name = 'maomaocong' where id = 6");
stmt.addBatch("insert into person values(5 ,'huixianmaomao')");
stmt.addBatch("delete from person where id = 5");
stmt.executeBatch();
//提交事务以后要恢复事务的自动提交状态
conn.commit();
conn.setAutoCommit(true);
rs = stmt.executeQuery("select * from person");
while(rs.next()){
System.out.print(rs.getString(1));
System.out.println(rs.getString(2));
}
} catch(ClassNotFoundException e){
e.printStackTrace();
} catch(SQLException e){
e.printStackTrace();
try{
if(conn != null){
conn.rollback();
conn.setAutoCommit(true);
System.out.println("rollback OK!");
}
} catch (SQLException e1){
e1.printStackTrace();
}
} finally {
try{
if(rs != null){
rs.close();
rs = null;
}
if(stmt != null){
stmt.close();
stmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException e){
e.printStackTrace();
}
}
}
}