20

我想在一批中发送两个不同的准备好的语句

目前,正如您在注释行中看到的那样,我正在分两步执行此操作,并且它有效,但这不是这里的主要目标。谁能告诉我用什么来代替这些评论才能让这件事发挥作用?

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, PreparedStatement preparedStatement, BigDecimal balance, int id) throws SQLException
    {
        preparedStatement = connection.prepareStatement("UPDATE bankAccount SET savingBalance = savingBalance + ? WHERE id = ?");
        preparedStatement.setBigDecimal(1, balance);
        preparedStatement.setInt(2, id);
        preparedStatement.addBatch();

        return preparedStatement;
    }
}
4

4 回答 4

10

你可以尝试执行这两条语句是一个单一的事务,像这样:

connection.setAutoCommit(false);
try {
    stmt1.execute();
    stmt2.execute();
    connection.commit();
} catch (Exception ex) {
    connection.rollback();
}

问题是 addBatch 适用于单个准备好的语句,请参阅这是如何将多个 sql 语句与 addBatch 一起使用。

于 2012-10-19T15:34:08.293 回答
10

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

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

于 2012-10-19T15:39:56.140 回答
1

我正在尝试使用准备好的语句和批处理!我说语句是因为我想在一批中发送两个准备好的语句。

当您谈论PreparedStatement时,批处理与此PreparedStatement对象的命令批处理相关联,而不是相反。您应该查看javadocaddBatch()方法以了解更多信息。

所以在你的情况下,这就是我会做的:

  • 创建新交易并设置批次限制
  • 为每个 PreparedStatement 创建一组批次并增加一个批次计数器
  • 当我达到限制并重置计数器时执行批处理
  • 完成后提交我的交易

所以你的代码看起来像这样:

preparedStatementWithdraw = connection.prepareStatement(....);
preparedStatementDeposit  = connection.prepareStatement(....);
boolean autoCommit        = connection.getAutoCommit();

int batchLimit = 1000; //limit that you can vary
int batchCounter = 0;
try{
    connection.setAutoCommit(false);

    //set the params and start adding your batch statements, as per your requirement, something like
    preparedStatementWithdraw.addBatch();
    preparedStatementDeposit.addBatch();
    batchCounter++;

    if(batchCounter == batchLimit){
        try{
            preparedStatementWithdraw.executeBatch();
            preparedStatementDeposit.executeBatch();
        }catch(Exception exe){
            //log your error
        }finally{
            preparedStatementWithdraw.clearBatch();
            preparedStatementDeposit.clearBatch();
            batchCounter = 0;
        }
    }
}finally{
        //process if any more statements are remaining in the batch
        try{
            preparedStatementWithdraw.executeBatch();
            preparedStatementDeposit.executeBatch();
        }catch(Exception exe){
            //log your error
        }finally{
            preparedStatementWithdraw.clearBatch();
            preparedStatementDeposit.clearBatch();
        }

    //1. depending on your requirement, commit/rollback the transation
    //2. Set autocommit to its original value
    connection.setAutoCommit(autoCommit);
    //3. Resoure management statements
}
于 2012-10-19T15:41:55.843 回答
0

我认为您可能希望将您的语句查询合并为一个并执行以下操作:

 String updateAccount= "UPDATE bankAccount 
                      SET if(? is not null ) 
                        then checkingBalance = checkingBalance - ? end if, 
                        if(? is not null ) 
                         then savingBalance = savingBalance + ? end if
                      WHERE id = ?";                
 PreparedStatement = dbConnection.prepareStatement(updateAccount);

 preparedStatement.setDouble(1, new Double(100));
 preparedStatement.setDouble(2, new Double(100));
 preparedStatement.setDouble(3, null);
 preparedStatement.setDouble(4, null);
 preparedStatement.setInt(5, 1);
 preparedStatement.addBatch();

 preparedStatement.setDouble(1, null);
 preparedStatement.setDouble(2, null);
 preparedStatement.setDouble(3, new Double(100));
 preparedStatement.setDouble(4, new Double(100));
 preparedStatement.setInt(5, 1);
 preparedStatement.addBatch();
 preparedStatement.executeBatch();

 dbConnection.commit();
于 2012-10-19T15:52:18.977 回答