>데이터 베이스 >MySQL 튜토리얼 >java语言MySQL数据库事务的处理_MySQL

java语言MySQL数据库事务的处理_MySQL

WBOY
WBOY원래의
2016-06-01 13:04:271023검색

事务处理流程

1、屏蔽自动提交功能

2、处理事务

3、恢复自动提交功能

代码实例

执行程序之前数据表的样子

\

 


public class GetConnection{
	public static void main(String[] args){
		Access2Database adb=new Access2Database();
		Connection conn=adb.getConn();	
		
		//transaction dealing
		PreparedStatement pstam=null;
		try{
			conn.setAutoCommit(false);
			String sql="delete from student where name='a' and major=?";
			pstam=conn.prepareStatement(sql);
			pstam.setString(1, "Chinese");
			pstam.executeUpdate();

			conn.rollback();
			conn.commit();
		}catch(SQLException e){
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				conn.setAutoCommit(true);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
		
		//release the resource of the program
		try{
			pstam.close();
			conn.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
}

之后的样子

 

\
可见没有发生改变,事务回滚成功

======================================================================

除此应用外,还可以保存事务处理的中间态,最后可以恢复到此中间保存状态

数据表之前的状态

\

看代码

 

import java.sql.*;

public class GetConnection{
	public static void main(String[] args){
		Access2Database adb=new Access2Database();
		Connection conn=adb.getConn();	
		
		//transaction dealing
		PreparedStatement pstam=null;
		try{
			conn.setAutoCommit(false);
			String sql="delete from student where name='a' and major=?";
			pstam=conn.prepareStatement(sql);
			pstam.setString(1, "Chinese");
			pstam.executeUpdate();
			//conn.commit();
			
			Savepoint sp=conn.setSavepoint();
			sql="insert into student(name,major,score) values('g','Math','99');";
			pstam=conn.prepareStatement(sql);
			pstam.executeUpdate();
			conn.rollback(sp);
			conn.commit();
		}catch(SQLException e){
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				conn.setAutoCommit(true);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
		
		//release the resource of the program
		try{
			pstam.close();
			conn.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
}
\

    
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.