java JDBC-演示事務出錯回滾操作

public class Demo6 { public static void main(String[] args) { Connection conn=null; PreparedStatement ps=null; PreparedStatement ps2=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","dyl123"); conn.setAutoCommit(false); ps=conn.prepareStatement("insert into t_user (username,pwd) values(?,?)"); ps.setString(1, "前端"); ps.setObject(2,"123456"); ps.execute(); System.out.println("插入一個用戶1"); try { Thread.sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } ps2=conn.prepareStatement("insert into t_user (username,pwd) values(?,?,?)"); //現出錯誤 ps2.setString(1, "html"); ps2.setObject(2,"2222"); ps2.execute(); System.out.println("插入一個用戶2"); conn.commit(); } catch (ClassNotFoundException e) { e.printStackTrace(); try { conn.rollback(); //事務回滾,使得事務出錯都不執行 } catch (SQLException e1) { e1.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); }finally { try { if(null!=rs) { rs.close(); } }catch (SQLException e) { e.printStackTrace(); } try { if(null!=ps) { ps.close(); } }catch (SQLException e) { e.printStackTrace(); } try{ if(null!=conn) { conn.close(); } }catch (SQLException e) { e.printStackTrace(); } } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章