我有一个无法运行的SQL事务查询。请问任何人请告诉我为什么?我也无法使用preparedstament.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;
答案 0 :(得分:4)
关闭自动提交,然后使用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
会锁定无论如何。
答案 1 :(得分:-3)
String query = "START TRANSACTION;SELECT total_installment_remaining FROMpayment_loan WHERE loan_id = 1 FOR UPDATE;UPDATE payment_loan SET total_installment_remaining =total_installment_remaining-1 WHERE loan_id = 1;COMMIT;";
try {
ps2 = con2.prepareStatement(query);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
rs2.getInt(1);
}
// rs.close();
// con.close();
} catch (SQLException e) {
logger.error("",e);
// TODO Auto-generated catch block
e.printStackTrace();
}