Postgresql transaction processing using java

I have two query blocks with readyStatement.

This is the first:

String sql = "update cikan_malzeme set miktar = ? where proje_id = ? and malzeme_id = ?"; PreparedStatement prep = dbConnect.connection.prepareStatement(sql); prep.setFloat(1, toplam); prep.setInt(2, pid); prep.setInt(3, mid); prep.executeUpdate(); 

And this is the second:

 String sql2 = "update malzemeler set miktar = ? where malz_adi = ?"; PreparedStatement prep2 = dbConnect.connection.prepareStatement(sql2); prep2.setFloat(1, fark); prep2.setString(2, malzemeadi); prep2.executeUpdate(); 

now I want to execute them with transaction BEGIN; and COMMIT; How can I handle a transaction using readyStatement?

Thanks in advance.

+6
source share
2 answers

Set auto commit to false.

Put your PreparedStatements in a try block. Lock at the end; rollback in the catch block.

As usual, this is done in the bare bone of JDBC.

http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html

If you are using EJB3 or Spring, you can add a transaction manager and specify them declaratively. It is more complex and flexible.

+8
source

You must use Connection.setAutoCommit(false) to disable the automatic commit of both Connection.commit() and Connection.rollback() .

When auto-commit is disabled, the transaction will start automatically when you first run a command or request that requires a transaction.

You should not use database-specific transaction management commands (since the driver will most likely do additional cleanups when issuing commit () or rollback ().

+6
source

Source: https://habr.com/ru/post/902180/


All Articles