我正在尝试在 JDBC 中为我正在开发的应用程序执行事务,但 Connection#setAutoCommit(false)
似乎不起作用。代码如下:
String insertCliente = "INSERT INTO Cliente VALUES (?,?,?,?,?,?)";
String vendiAuto = "{CALL VendiAuto(?,?,?,?)}";
try
{
connection.setAutoCommit(false);
PreparedStatement statement1 = connection.prepareStatement(insertCliente);
CallableStatement statement2 = connection.prepareCall(vendiAuto);
statement1.setString(1,CF);
statement1.setString(2,nome);
statement1.setString(3,cognome);
statement1.setDate(4,new Date(new GregorianCalendar(anno,mese,giorno).getTimeInMillis()));
statement1.setString(5,luogo);
statement1.setString(6,sesso);
statement2.setString(1,codice);
statement2.setString(2,venditore);
statement2.setString(3,CF);
statement2.setBigDecimal(4,prezzoVendita);
statement1.execute();
statement2.execute();
connection.commit();
}
catch (SQLException e)
{
connection.rollback();
throw e;
}
finally
{
connection.setAutoCommit(true);
}
如果statement2.execute()
失败,尽管connection.rollback()
被调用,statement1.execute()
仍然有效。
也许我做错了什么。
我不知道如何解决。你能帮我吗?
使用的DBMS是MySQL 8.0.18,表引擎是InnoDB。
最佳答案
我发现connection.setAutoCommit(false)
与我的存储过程有冲突:在该过程中,已经有一个事务(用START TRANSACTION
定义)并且不知怎的,它与声明相冲突。
我解决了从存储过程中删除事务的问题。
关于java - 为什么 setAutoCommit(false) 在 JDBC 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59343822/