使用 java 处理 Postgresql 事务 [英] Postgresql transaction handling with java
问题描述
我有两个带有preparedStatement的查询块.
I have two blocks of queries with preparedStatement.
这是第一个:
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();
这是第二个:
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();
现在我想用事务BEGIN来执行它们;和提交;如何使用 PreparedStatement 处理事务?
Now I want to execute them with the transaction BEGIN; and COMMIT; How can I handle transaction with preparedStatement?
推荐答案
将自动提交设置为 false.
Set auto commit to false.
将您的 PreparedStatements 放在 try 块中.最后提交;在 catch 块中回滚.
Put your PreparedStatements in a try block. Commit at the end; rollback in the catch block.
这就是通常在基本 JDBC 中完成的方式.
That's how it's usually done in bare bones JDBC.
http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html
如果您使用 EJB3 或 Spring,您可以添加一个事务管理器并以声明方式指定它们.这更加复杂和灵活.
If you use EJB3 or Spring you can add a transaction manager and specify them declaratively. That's more sophisticated and flexible.
这篇关于使用 java 处理 Postgresql 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!