DBMNG数据库管理与应用

书籍是全世界的营养品。生活里没有书籍,就好像没有阳光;智慧里没有书籍,就好像鸟儿没有翅膀。
当前位置:首页 > MySQL > 基础知识

Java中SQL用事务处理转账操作示例

这里以MySQL(InnoDB引擎)为例:


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.PreparedStatement;
public class testcommit
{
	/**
	* @param args
	* @throws SQLException
	*/
	public static void main(String[] args) throws SQLException
	{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		Connection connection = null;
		// Statement statement=null;
		// String sql="";
		try
		{
			connection = dataSource.getConnection();
			// statement=connection.createStatement();
			connection.setAutoCommit(false);
			// sql="insert into t1(a,b)values('345','gdf')";
			// statement.executeUpdate(sql);
			// sql="insert into t2(c,d)values('43243','dddddddd')";
			// statement.executeUpdate(sql);
			// System.out.println(statement.executeBatch());
			if (zhuanchu("aaa", 10.00, connection) == 0)
			throw new SQLException("转出操作失败");
			if (zhuanru("bbb", 10.00, connection) == 0)
			throw new SQLException("转入操作失败");
			connection.commit();
			connection.setAutoCommit(true);
			connection.close();
			System.out.println("转账操作成功!");
		} catch (SQLException e)
		{
		connection.rollback();
		connection.setAutoCommit(true);
		connection.close();
		e.printStackTrace();
		System.out.println(e);
		}
	}
	public static int zhuanchu(String zhanghao, double jine, Connection conn)
	{
		int rtnVal = 1;
		PreparedStatement pStatement = null;
		ResultSet rs = null;
		try
		{
			pStatement = conn.prepareStatement("select yue from t1 where yonghuming=?");
			pStatement.setString(1, zhanghao);
			rs = pStatement.executeQuery();
			if (rs.next())
			{
			if (rs.getDouble("yue") - jine < 0)
			{
			System.out.println(zhanghao + "的余额不足");
			rtnVal = 0;
			} else
			{
			pStatement = conn.prepareStatement("update t1 set yue=yue-? where yonghuming=?");
			pStatement.setDouble(1, jine);
			pStatement.setString(2, zhanghao);
			if (pStatement.executeUpdate() == 0)
			rtnVal = 0;
			}
			} else
			{
			rtnVal = 0;
			}
			pStatement.close();
		} catch (Exception e)
		{
			System.out.println(e);
			rtnVal = 0;
		}
		return rtnVal;
	}
	public static int zhuanru(String zhanghao, double jine, Connection conn)
	{
		int rtnVal = 1;
		PreparedStatement pStatement = null;
		try
		{
		pStatement = conn.prepareStatement("update t1 set yue=yue+? where yonghuming=?");
		pStatement.setDouble(1, jine);
		pStatement.setString(2, zhanghao);
		if (pStatement.executeUpdate() == 0)
		rtnVal = 0;
		pStatement.close();
		} catch (Exception e)
		{
		System.out.println(e);
		rtnVal = 0;
		}
		return rtnVal;
	}
}


这里再重点推荐一篇更加详细的解释Java操作MySQL使用事务实现银行转账的示例文章java操作MySQL事务的并发和隔离-银行金融账户转账示例

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号