事物的理解案列

package com.java.test_1;

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

public class Procedure {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		//事物的案列 张三转钱到李四的账户
		
		Connection connection = null;
//		StringBuffer sb=new StringBuffer();
		try {

			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/lesson_4_4", "root", "123456");

			connection.setAutoCommit(false);// 关闭自动提交
			
//			sb.append("update tb_account set accountmoney=accountmoney+500 where `name`=?;");
//			sb.append("update tb_account set accountmoney=accountmoney-500 where `name`=?;");
			
			String sqlString = "update tb_account set accountmoney=accountmoney+500 where `name`='张三';";
			String sqlString2="update tb_account set accountmoney=accountmoney-500 where `name`='李四';";
			
			PreparedStatement preparedStatement = connection.prepareStatement(sqlString);
			
			preparedStatement.execute();
			preparedStatement.close();
			
			preparedStatement=connection.prepareStatement(sqlString2);
			preparedStatement.execute();

			
			connection.commit();// 提交文件

		} catch (Exception e) {

			connection.rollback(); // 执行回滚操作
			System.out.println("程序出错:" + e.getMessage());
			e.printStackTrace();
		}

	}

}

使用了关键代码关闭自动提交事物,再执行同步的修改语句,在数据库那边设置了余额不可以存在符号的操作,所有当金额出现负数的时候,程序会报错,在catch里面执行回滚操作,使此次交易作废!

发布了108 篇原创文章 · 获赞 46 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_44739706/article/details/103172795
今日推荐