事务处理

package com.atguigu.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.junit.Test; public class TransactionTest { /** * Tom给Jerry汇款500元 * 关于事务: * 1、如果多个操作,每个操作使用的是自己的单独的连接,则无法保证事务。 * 2、 具体步骤: * 1)事务操作开始前,开始事务:取消Connection的默认提交行为。 * 2)如果事务的操作都成功则成交事务。 * 3)回滚,若出现异常,则在catch块中回滚事务 * @throws IOException * @throws SQLException * @throws ClassNotFoundException */ @Test public void testTransaction() throws ClassNotFoundException, IOException { Connection connection=null; try{ connection=JDBCTools.getConnection(); //开始事务: 取消默认提交 connection.setAutoCommit(false); int params=500; String sql="update users set balance=balance+? where username='Jerry'"; update(connection,sql, params); int i=10/0; sql="update users set balance=balance-? where username='Tom'"; update(connection,sql, params); System.out.println(5); //提交事务 connection.commit(); }catch(SQLException e){ e.printStackTrace(); try { //事务回滚 connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }finally{ JDBCTools.release(null, null, connection); } } public void update(Connection connection,String sql, Object... params) { PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { preparedStatement.setObject(i + 1, params[i]); } preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.release(null, preparedStatement, null); } } }
原文地址:https://www.cnblogs.com/xiaona19841010/p/5204275.html