事务
1.原子性
事务是应用中不可再分的最小逻辑执行体
2.一致性
事务的执行结果必须使数据库从一个一致性状态变到另一个一致性状态
3.隔离性
各个 事务的执行不干扰
4.持续性
事务一旦提交,对数据库所做的任何改变都记录到永久存储器中,即保存到了物理数据库
Java中的事务
package ch13;import java.sql.*;/** * Created by Jiqing on 2016/12/26. */public class TransactionTest { private String driver; private String url; private String user; private String pass; // 初始化参数 public void initParam() { driver = "com.mysql.jdbc.Driver"; url = "jdbc:mysql://127.0.0.1:3306/test"; user = "root"; pass = "123456"; } public void insertInTransation(String[] sqls) throws Exception { // 加载驱动 Class.forName(driver); try ( Connection conn = DriverManager.getConnection(url,user,pass)) { // 关闭自动提交 conn.setAutoCommit(false); try( // 使用Connection来创建一个Statement Statement stmt = conn.createStatement()) { for (String sql : sqls) { stmt.executeUpdate(sql); } } // 回滚 // conn.rollback(); // 提交事务 conn.commit(); } } public static void main(String[] args) throws Exception { TransactionTest tt = new TransactionTest(); tt.initParam(); String[] sqls = new String[] { "insert into student values('1','Li')", "insert into student values('2','Zhao')", "insert into student values('3','Ji')" }; tt.insertInTransation(sqls); }}
增加回滚
package ch13;import java.sql.*;/** * Created by Jiqing on 2016/12/26. */public class TransactionTest { private String driver; private String url; private String user; private String pass; // 初始化参数 public void initParam() { driver = "com.mysql.jdbc.Driver"; url = "jdbc:mysql://127.0.0.1:3306/test"; user = "root"; pass = "123456"; } public void insertInTransation(String[] sqls) throws Exception { // 加载驱动 Class.forName(driver); try ( Connection conn = DriverManager.getConnection(url,user,pass)) { // 关闭自动提交 conn.setAutoCommit(false); try( // 使用Connection来创建一个Statement Statement stmt = conn.createStatement()) { for (String sql : sqls) { stmt.executeUpdate(sql); } } // 回滚 conn.rollback(); // 提交事务 conn.commit(); } } public static void main(String[] args) throws Exception { TransactionTest tt = new TransactionTest(); tt.initParam(); String[] sqls = new String[] { "insert into student values('4','Qian')", "insert into student values('5','Sun')", "insert into student values('6','Liu')" }; tt.insertInTransation(sqls); }}
内容不会被保存。