mysql事务的四大特性与简单运用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | package mysql; import java.sql.Connection; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import org.junit.Test; //事物特性ACID //原子性,指事务中的操作要么都发生,要么都不发生 //一致性。指事务前后数据的完整性必须保持一致(甲乙2人总额2000元,甲转账乙100元后,转账后总额还是2000元) //隔离性。多个事务并发访问数据库的时候,一个事务间的操作不能干扰其他事务,要相互隔离 //持久性:指事务一旦提交(commit),对数据库的改变是持久的,即使数据库故障也不应对数据有影响 //数据库的隔离级别Seraializable(串行化,最高级别,能处理各种问题,但数据库效率低下),repeated read,read commit,read uncommit /* create table account ( id int primary key auto_increment, name varchar(20), price int ); /* * 事务,要么执行,要不执行 * start transaction update account set price=price-100 where name='a'; update account set price=price+100 where name='b'; * sql2语句 * commit(一定要执行commit才生效,不然回滚) */ public class 事务 { @Test public void test1() throws SQLException { Statement s= null ; Connection con=DBHelper.getConnection(); try { con.setAutoCommit( false ); //不能一条一条执行sql String sql1= "update account set price=price-100 where name='a'" ; String sql2= "update account set price=price+100 where name='b'" ; s=con.createStatement(); s.executeUpdate(sql1); int i= 8 / 0 ; //这边有错,程序自动回滚 s=con.createStatement(); s.executeUpdate(sql2); con.commit(); System.out.println( "success...." ); } catch (Exception e) { con.rollback(); //自动回滚 } } @Test public void test2() throws SQLException //手动回滚事务,假如第二条sql执行错误,程序回滚,让第一条sql正常插入数据库 { Statement s= null ; Connection con=DBHelper.getConnection(); Savepoint p= null ; try { con.setAutoCommit( false ); //不能一条一条执行sql String sql1= "update account set price=price-100 where name='a'" ; String sql2= "update account set price=price+100 where name='b'" ; String sql3= "update account set price=price+100 where name='c'" ; s=con.createStatement(); s.executeUpdate(sql1); p=con.setSavepoint(); //保存点 int i= 12 / 0 ; //这边出错了,上一条依然插入数据库 s=con.createStatement(); s.executeUpdate(sql2); s=con.createStatement(); s.executeUpdate(sql3); con.commit(); System.out.println( "success...." ); } catch (Exception e) { con.rollback(p); //回滚到第一个,第一个要执行 con.commit(); //手动回滚一定要提交 } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步