JDBC事务的操作
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://sophi.blog.51cto.com/340461/66326 |
import java.sql.*; 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(); } } } } 本文出自 ““技”忆” 博客,请务必保留此出处http://sophi.blog.51cto.com/340461/66326 本文出自 51CTO.COM技术博客 |


huixianmaomao
博客统计信息
热门文章
最新评论
友情链接