日期:2014-05-16  浏览次数:20462 次

JDBC 事务 和 savePoint
package com.enhance.jdbc;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.Properties;

public class TransactionTest {

	private String driver;
	private String url;
	private String user;
	private String pass;
	private Connection conn;
	private Statement stmt;
	
	public void initParam(String paramFile) throws Exception{
		Properties prop=new Properties();
		prop.load(new FileInputStream(paramFile));
		driver=prop.getProperty("driver");
		url=prop.getProperty("url");
		user=prop.getProperty("user");
		pass=prop.getProperty("pass");
	}
	public void insertInTranscation(String[] sqls){
		Savepoint sp=null;
		try{
			Class.forName(driver);
			conn=DriverManager.getConnection(url,user,pass);
			
			//关闭自动提交 ,并开启事务	
			conn.setAutoCommit(false);
			System.out.println("开启了事务!");
			stmt=conn.createStatement();
			for (String sql : sqls) {
				stmt.execute(sql);
				sp=conn.setSavepoint(); //如果使用  "保存点" 
			}
			//conn.commit(); //提交事务	如果没有使用   "保存点" 
			//System.out.println("提交了事务!");
		}catch(Exception e){
			if(sp!=null){
				try {
					conn.rollback(sp);  //回滚到上一个保存点  但是事务还是没有结束 
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}finally{
			try {
				conn.commit(); //提交事务	  //使用 "保存点"后依然提交
				System.out.println("提交了事务!");
				if(stmt!=null)
					stmt.close();
				if(conn!=null)
					conn.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			
		}
		
	}
	
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		TransactionTest tt=new TransactionTest();
		tt.initParam("src/mysql.ini");
		String[]sqls={
				"insert into my_test values(null,'提交事务')"
				,"insert into my_test values(null,'加油')"
				,"update my_test set test_name='comme on!!' where id=5"};//
		tt.insertInTranscation(sqls);
	}

}