java监听mysql事务_java语言MySQL数据库事务的处理

事务处理流程

1、屏蔽自动提交功能

2、处理事务

3、恢复自动提交功能

代码实例

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

90e85973619371732db8cb1327412ed2.png

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();

}

}

}

之后的样子

752198848a1f20b07913c3bf1ade59c1.png

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

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

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

数据表之前的状态

7c4df8ae04adc2529193ceca917bf47d.png

看代码

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();

}

}

}

21c5a77038177a261fa5502b2cf79cbe.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值