How to use transactions
in java programs to ensure data consistency when operating databases in java, such as transfer operations
1) Deduct 10$ from one account
2) Add 10$ to another account
How to use transactions?
package Test; import java.sql.Statement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Connection; public class TestTrans { public static void main(String[] args) { // transaction case Connection ct = null; try { //load driver Class.forName("oracle.jdbc.driver.OracleDriver"); // get the connection ct = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger"); // join transaction //The system defaults to automatic commit, so to join transaction processing, you need to set the default commit to false ct.setAutoCommit(false);//The setting cannot be submitted by default Statement sm = ct.createStatement(); //from scott's sal-100 sm.executeUpdate("update kkkk set sal=sal-100 where ename='SCOTT'"); // int i=7/0; //sal+100 from SMITH sm.executeUpdate("update kkkk set sal=sal+100 where ename='SMITH'"); // commit the transaction ct.commit(); //close the resource sm.close(); ct.close(); } catch (Exception e) { //If an exception occurs, roll back try { ct.rollback();//rollback itself will be abnormal } catch (Exception ex) { ex.printStackTrace(); } e.printStackTrace (); } } }