JDBC 事务回滚
package jdbcstu; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class TransactionTest { public static void main(String[] args) { Connection conn=null; try { conn=getConnection(); conn.setAutoCommit(false);//禁止事务的自动提交 insertUserData(conn); insertAddressData(conn); } catch (SQLException e) { System.out.println("======捕获到SQL异常===="); e.printStackTrace(); try { conn.rollback(); System.out.println("===事务回滚成功====="); } catch (Exception e2) { // TODO: handle exception } }finally{ try { if(conn!=null){ conn.close(); } } catch (Exception e3) { e3.printStackTrace(); } } } public static Connection getConnection(){ Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db","root",""); } catch (Exception e) { // TODO: handle exception } return conn; } public static void insertUserData(Connection conn) throws SQLException { String sql="insert into tbl_user(id,name,password,email)"+ "values(10,‘Tom‘,‘123456‘,‘[email protected]‘)"; Statement st=conn.createStatement(); int count=st.executeUpdate(sql); System.out.println("向用户表中插入了"+count+"条记录"); } public static void insertAddressData(Connection conn) throws SQLException { String sql="insert into tbl_address(id,city,country,user_id)"+ "values(1,‘shanghai‘,‘china‘,‘10‘)"; Statement st=conn.createStatement(); int count=st.executeUpdate(sql); System.out.println("向地址表中插入了"+count+"条记录"); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。