• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞代码 4年前 (2022-01-09) 29次浏览 已收录 0个评论

事务处理流程

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.printSta<mark>本文来源gaodaimacom搞#代%码@网-</mark>ckTrace();		}	}}



搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java语言MySQL数据库事务的处理_MySQL

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址