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

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

问题描述

我们都知道 我们应该重用 JDBC PreparedStatement 而不是在循环中创建新实例.

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

但是如何处理不同方法调用之间的PreparedStatement重用?重用——规则"还算数吗?

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

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

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.

推荐答案

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

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.

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

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 对象绑定到一个连接,应该尽快使用连接并返回到池中.

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

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

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天全站免登陆