java – 两个不同的准备语句在一个单一的批处理
发布时间:2020-12-14 05:11:14 所属栏目:Java 来源:网络整理
导读:我想在一个批次中发送两个不同的准备好的语句. 目前我正在做两件事,你可以在注释的行中看到它的作用,但这不是这里的主要目的.任何人都可以告诉我要做些什么来取代这些意见吗? import java.lang.ClassNotFoundException;import java.math.BigDecimal;import
我想在一个批次中发送两个不同的准备好的语句.
目前我正在做两件事,你可以在注释的行中看到它的作用,但这不是这里的主要目的.任何人都可以告诉我要做些什么来取代这些意见吗? 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所提到的,您可以 – 并且必须 – 在单个事务中执行它们.
另一个选择是使用可以在服务器的单一往返中完成所有操作的存储过程,同时保持单个事务的好处 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |