我想在一个批次中发送两个不同的准备好的语句.
目前我正在做两件事,你可以在注释的行中看到它的作用,但这不是这里的主要目的.任何人都可以告诉我要做些什么来取代这些意见吗?
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.jb51.cc/java/123252.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。