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所提到的,您可以 – 并且必须 – 在单个事务中执行它们.

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...