0324

MySQL事务:
      四个特性。P630
      事务执行成功应提交:
            显式提交:commit;
            自动提交:执行DDL或DCL语句,或程序正常退出。
      执行失败应回滚:
           显式:rollback;
           自动:系统出错或强行退出。
      命令行:    
      begin;   #临时开始事务
      insert into student_table    #插入3条记录
      values (null,'xx',1);
      insert into student_table
      values (null,'yy',1);
      insert into student_table
      values (null,'zz',1);
      select * from student_table;    #看到记录已经出入表中,不过这时候再开一个窗口就看不到(隔离性)
      rollback;     #刚才做的都撤销
      select * from student_table;     #那3条又没了。   上一行rollback换成commit就一直有。
  savepoint a;设置事务中间点;
  rollback to a; 回滚到中间点。
      调用Connection的setAutoCommit()方法
            con.setAutoCommint(false);关闭自动提交,即开启事务。
      boolean getAutoCommit();返回该连接的自动提交模式
      commit();
      rollback();
      Savepoint setSavepoint();
      Savepoint setSavepoint(String name);
      rollback(Savepoint savepoint);
      如果遇到未处理的SQLException,就回非正常退出,自动rollback。 

下列代码没有rollback代码,因为异常自动rollback。    
import java.sql.*;
import java.io.*;
import java.util.*;
public class TransactionTest
{
	private String driver;
	private String url;
	private String user;
	private String pass;
	public void initParam(String paramFile)throws Exception
	{
		// 使用Properties类来加载属性文件
		Properties props = new Properties();
		props.load(new FileInputStream(paramFile));
		driver = props.getProperty("driver");
		url = props.getProperty("url");
		user = props.getProperty("user");
		pass = props.getProperty("pass");
	}
	public void insertInTransaction(String[] sqls) throws Exception
	{
		// 加载驱动
		Class.forName(driver);
		try(
			Connection conn = DriverManager.getConnection(url , user , pass))
		{
			// 关闭自动提交,开启事务
			conn.setAutoCommit(false);
			try(
				// 使用Connection来创建一个Statment对象
				Statement stmt = conn.createStatement())
			{
				// 循环多次执行SQL语句
				for (String sql : sqls)
				{
					stmt.executeUpdate(sql);
				}
			}
			// 提交事务
			conn.commit();
		}
	}
	public static void main(String[] args) throws Exception
	{
		TransactionTest tt = new TransactionTest();
		tt.initParam("mysql.ini");
		String[] sqls = new String[]{
			"insert into student_table values(null , 'aaa' ,1)",
			"insert into student_table values(null , 'bbb' ,1)",
			"insert into student_table values(null , 'ccc' ,1)",
			// 下面这条SQL语句将会违反外键约束,
			// 因为teacher_table中没有ID为5的记录。
			"insert into student_table values(null , 'ccc' ,5)" //①
		};
		tt.insertInTransaction(sqls);
	}
}

       

猜你喜欢

转载自huadianfanxing.iteye.com/blog/2365630
024
324