使用 java 处理 Postgresql 事务

发布于 2024-12-17 17:28:35 字数 642 浏览 4 评论 0原文

我有两个带有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处理事务?

I have two blocks of queries with preparedStatement.

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 the transaction BEGIN; and COMMIT;
How can I handle transaction with preparedStatement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暗喜 2024-12-24 17:28:35

您应该使用 连接.setAutoCommit(false) 禁用自动提交和 Connection.commit()Connection.rollback()

禁用自动提交后,第一次执行需要事务的命令或查询时,事务将自动启动。

您不应该使用数据库特定的事务控制命令,因为驱动程序很可能在发出 commit() 或 rollback() 时对资源进行额外的清理。

You should use Connection.setAutoCommit(false) to disable auto-commit and Connection.commit() and Connection.rollback().

When auto-commit is disabled, a transaction will be started automatically the first time you execute a command or query that requires a transaction.

You should not be using the database specific transaction control commands, as the driver will most likely do additional cleanup of resources when a commit() or rollback() is issued.

神回复 2024-12-24 17:28:35

将自动提交设置为 false。

将您的PreparedStatements 放入try 块中。最后承诺;在 catch 块中回滚。

这就是通常在简单的 JDBC 中完成的方式。

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

如果您使用 EJB3 或 Spring,您可以添加事务管理器并以声明方式指定它们。这更加复杂和灵活。

Set auto commit to false.

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

That's how it's usually done in bare bones JDBC.

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

If you use EJB3 or Spring you can add a transaction manager and specify them declaratively. That's more sophisticated and flexible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文