首页 > 数据库技术 > 详细

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

时间:2014-11-18 14:44:34      阅读:216      评论:0      收藏:0      [点我收藏+]

事务处理流程

1、屏蔽自动提交功能

2、处理事务

3、恢复自动提交功能

代码实例

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

bubuko.com,布布扣

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();
<span style="white-space:pre"></span><pre name="code" class="java"><span style="white-space:pre">			</span>conn.rollback();

<span style="white-space:pre">			</span>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();
		}
	}
}
之后的样子

bubuko.com,布布扣
可见没有发生改变,事务回滚成功

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

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

数据表之前的状态

bubuko.com,布布扣

看代码

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();
		}
	}
}
bubuko.com,布布扣



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

原文:http://blog.csdn.net/cjc211322/article/details/41246191

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!