在方法之间重用PreparedStatement? [英] Reusing of a PreparedStatement between methods?

查看:156
本文介绍了在方法之间重用PreparedStatement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道 那我们宁愿重用JDBC PreparedStatement 而不是在循环中创建新实例。



但是如何处理 PreparedStatement 在不同的方法调用之间重用?
重用 - 规则是否仍然有效?



我是否真的考虑使用 PreparedStatement 或者我应该在每次调用时关闭并重新创建准备好的语句(保持本地化)?
(当然这样一个类的实例将绑定到 Connection ,这在某些架构中可能是一个缺点)



我知道理想的答案可能是它取决于。

但我正在寻找经验不足的开发人员的最佳实践,他们将在大多数情况下做出正确的选择。 case。

解决方案


当然这样一个类的实例会绑定到一个可能的Connection是一个缺点


可能是?这将是巨大的劣势。您需要同步对它的访问权限,这会使您的多用户性能死亡,或者创建多个实例并将它们保存在池中。屁股的主要痛苦。



语句池是JDBC驱动程序的工作,大多数(如果不是全部)当前的驱动程序都会为您执行此操作。当您调用 prepareStatement prepareCall 时,驱动程序将处理现有资源和预编译语句的重用。 / p>

语句对象绑定到一个连接,应该使用连接并尽快返回到池中。



简而言之,在方法开始时获取 PreparedStatement 的标准做法,在a中重复使用它循环,然后在方法结束时关闭它,最佳实践。


We all know that we should rather reuse a JDBC PreparedStatement than creating a new instance within a loop.

But how to deal with PreparedStatement reuse between different method invocations? Does the reuse-"rule" still count?

Should I really consider using a field for the PreparedStatement or should I close and re-create the prepared statement in every invocation (keep it local)? (Of course an instance of such a class would be bound to a Connection which might be a disadvantage in some architectures)

I am aware that the ideal answer might be "it depends".
But I am looking for a best practice for less experienced developers that they will do the right choice in most of the cases.

解决方案

Of course an instance of such a class would be bound to a Connection which might be a disadvantage

Might be? it would be a huge disadvantage. You'd either need to synchronize access to it, which would kill your multi-user performance stone-dead, or create multiple instances and keep them in a pool. Major pain in the ass.

Statement pooling is the job of the JDBC driver, and most, if not all, of the current crop of drivers do this for you. When you call prepareStatement or prepareCall, the driver will handle re-use of existing resource and pre-compiled statements.

Statement objects are tied to a connection, and connections should be used and returned to the pool as quickly as possible.

In short, the standard practice of obtaining a PreparedStatement at the start of the method, using it repeatedly within a loop, then closing it at the end of the method, is best practice.

这篇关于在方法之间重用PreparedStatement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆