java – 两个不同的准备语句在一个单一的批处理

前端之家收集整理的这篇文章主要介绍了java – 两个不同的准备语句在一个单一的批处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在一个批次中发送两个不同的准备好的语句.

目前我正在做两件事,你可以在注释的行中看到它的作用,但这不是这里的主要目的.任何人都可以告诉我要做些什么来取代这些意见吗?

import java.lang.ClassNotFoundException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.sqlException;
import java.sql.DriverManager;

public class Main
{
    public static void main(String[] args)
    {
        Connection connection = null;
        PreparedStatement preparedStatementWithdraw = null;
        PreparedStatement preparedStatementDeposit = null;

        try
        {
            Class.forName("com.MysqL.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:MysqL://localhost:3306/youtube","root","root");

            preparedStatementWithdraw = withdrawFromChecking(connection,preparedStatementWithdraw,new BigDecimal(100),1);
            preparedStatementDeposit = depositIntoSaving(connection,preparedStatementDeposit,new BigDecimal(300),1);

            //preparedStatementDeposit.executeBatch();
            //preparedStatementWithdraw.executeBatch();
            System.out.println("Account Modified!");
        }
        catch(ClassNotFoundException error)
        {
            System.out.println("Error: " + error.getMessage());
        }
        catch(sqlException error)
        {
            System.out.println("Error: " + error.getMessage());
        }
        finally
        {
            if(connection != null) try{connection.close();} catch(sqlException error) {}
            if(preparedStatementDeposit != null) try{preparedStatementDeposit.close();} catch(sqlException error) {}
        }
    }

    public static PreparedStatement withdrawFromChecking(Connection connection,PreparedStatement preparedStatement,BigDecimal balance,int id) throws sqlException
    {
        preparedStatement = connection.prepareStatement("UPDATE bankAccount SET checkingBalance = checkingBalance - ? WHERE id = ?");
        preparedStatement.setBigDecimal(1,balance);
        preparedStatement.setInt(2,id);
        preparedStatement.addBatch();

        return preparedStatement;
    }

    public static PreparedStatement depositIntoSaving(Connection connection,int id) throws sqlException
    {
        preparedStatement = connection.prepareStatement("UPDATE bankAccount SET savingBalance = savingBalance + ? WHERE id = ?");
        preparedStatement.setBigDecimal(1,id);
        preparedStatement.addBatch();

        return preparedStatement;
    }
}

解决方法

您不能在单个批处理中执行两个不同的语句.正如@dan所提到的,您可以 – 并且必须 – 在单个事务中执行它们.

另一个选择是使用可以在服务器的单一往返中完成所有操作的存储过程,同时保持单个事务的好处

原文链接:https://www.f2er.com/java/123252.html

猜你在找的Java相关文章