gpt4 book ai didi

java - 如何在PreparedStatement中运行SQL TRANSACTION

转载 作者:行者123 更新时间:2023-11-30 07:39:20 24 4
gpt4 key购买 nike

我有一个无法运行的 SQL 事务查询。谁能告诉我为什么吗?我也无法使用 preparedstatement.executequery(); 运行它。

START TRANSACTION;
SELECT total_installment_remaining FROM payment_loan WHERE loan_id = 1 FOR UPDATE;
UPDATE payment_loan SET total_installment_remaining =total_installment_remaining-1 WHERE loan_id = 1;
COMMIT;

最佳答案

关闭自动提交,然后使用 Connection.commit() 结束事务。

connection.setAutocommit(false);
Statement stmt = con2.createStatement();

// this will automatically start a transaction
ResultSet rs = stmt.executeQuery("SELECT total_installment_remaining FROM payment_loan WHERE loan_id = 1 FOR UPDATE");

// process the result if needed
...

stmt.executeUpdate("UPDATE payment_loan SET total_installment_remaining =total_installment_remaining-1 WHERE loan_id = 1");

// end the transaction and persist then changes
connection.commit();
<小时/>

如果您的代码中不需要 SELECT 的结果,那么您首先就不需要 SELECT ... FOR UPDATE,因为 UPDATE 无论如何都会锁定该行。

关于java - 如何在PreparedStatement中运行SQL TRANSACTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com