20_传智播客JDBC_事务的概念与JDBC事务处理

本文介绍了一个使用Java进行数据库事务处理的示例程序,演示了如何通过手动控制事务来实现转账操作,并处理可能出现的异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package five.base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import five.dao.myException.MyUserException;
import five.utils.UtilsSingle;

public class TxTest {

 
 public static void main(String[] args) {
  TxTest xuxl = new TxTest();
  try {
   xuxl.test(1, 2, 2000);
  } catch (SQLException e) {

   e.printStackTrace();
  }
 }
 public void  test( int from, int to, float monney) throws SQLException {
   
     PreparedStatement ps = null;
     ResultSet rs = null;
     UtilsSingle instance = UtilsSingle.getUtilsSingleInstance();
     Connection connection = null;
       
        try {
         //  创建连接
         connection = instance.getConnection();
         
         // 手动控制事务
         connection.setAutoCommit(false);

         //  创建语句
         String sql = "update user set monny = monny - ?  where id = ?";
         ps = connection.prepareStatement(sql);

         // 向占位符 设置参数
         ps.setFloat(1, monney);
         ps.setInt(2, from);

         //  执行语句
         int updateNum = ps.executeUpdate();
         System.out.println("update Row number is" + updateNum);
         sql = "select monny from user where id = ?";
         ps = connection.prepareStatement(sql);
         ps.setInt(1, to);

         //  执行语句
         rs = ps.executeQuery();
         float toMooey = 0.0f;
         System.out.println("result of Row number is" + rs.getRow());
   if (rs.next()) {
    toMooey = rs.getFloat("monny");
    if (toMooey > 1000.0f) {
     // 抛出异常后,事务不提交
     throw new RuntimeException("id is " + to
       + " of moy > 1000.0f");
    }
   }
   sql = "update user set monny =monny + ?  where id = ?" ;
   ps=connection.prepareStatement(sql);
   ps.setFloat(1, monney);
   ps.setInt(2, to);
   ps.executeUpdate();

   // 数据库的引擎 (通过 show create table user  )
   // InnoDB 有的支持事务外键 有的不支持
   // 不支持数据库的引擎 CRDU快
   connection.commit();

        } catch (SQLException e) {
         if (connection != null) {
          System.out.println("回滚了");
    connection.rollback();
   }
         throw new MyUserException(e.getMessage(), e);
  } finally {
         instance.free(connection, ps, rs);
        }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值