(JDBC)20_事务的概念与JDBC事务处理
一.事务(ACID)
1.原子性:组成事务处理的语句形成了一个逻辑单元,不能只执行其中的一个部分
2.一致性:在事务处理执行前后,数据库是一致的(数据库数据完整性约束)
3.隔离性:一个事务处理对另一个事物处理的影响
4.持续性:事务处理的效果能够永久保存下来
connection.setAutoCommit(false);//打开事务
connection.commit();//提交事务
connection.rollback();//回滚事务
举例:
public class TxTest { public static void main(String[] args) throws SQLException { test(); } static void test() throws SQLException{ System.out.println("123"); Connection con=get_con(); try { Statement st=con.createStatement(); con.setAutoCommit(false); String sql="update usertr set money=money-10 where id=1"; st.executeUpdate(sql); sql="select money from usertr where id=2"; ResultSet rs=st.executeQuery(sql); int money=0; if(rs.next()){ money=rs.getInt("money"); System.out.println(money); } if(money>100){//即第二个人的钱多余100就不转账 throw new RuntimeException("多了"); } sql="update usertr set money=money+10 where id=2"; st.executeUpdate(sql); con.commit(); con.close(); rs.close(); st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); if(con!=null){ con.rollback(); } throw e; } } static Connection get_con(){ Connection con=null; try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/new_schema","root","zxy123456"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } }