何时关闭 JDBC 中的 Connection、Statement、PreparedStatement 和 ResultSet [英] When to close Connection, Statement, PreparedStatement and ResultSet in JDBC

查看:27
本文介绍了何时关闭 JDBC 中的 Connection、Statement、PreparedStatement 和 ResultSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 JDBC 编码的几个问题:

Few questions on JDBC coding:

  1. 对于单个客户端应用程序,我们是否需要连接池?
  2. 在开始时创建一个 Connection 并使其保持活动状态而不关闭它直到应用程序退出是否是个好主意?为什么?
  3. PreparedStatementConnection 相关联,如果我的连接在每次查询后都没有关闭,为什么不保持 PreparedStatement 活动并在其他方法?
  4. 如果我们为每个查询创建PreparedStatement,数据库是否知道它是相同的PreparedStatement并在第一次之后忽略不必要的操作?
  5. PreparedStatement 不是创建一次重复使用多次的语句吗?如果是,为什么每次都需要关闭它?
  1. For a single client application, do we need a Connection pool?
  2. Is it a good idea to create a Connection at the beginning and keep it alive without close it until application exit? Why?
  3. PreparedStatement is associated with Connection, if my connection is not closed after each query, why not keep the PreparedStatement alive and reuse it in other methods?
  4. if we create PreparedStatement each query, does the database knows it is the same PreparedStatement and ignore unnecessary actions after the first time?
  5. PreparedStatement is not create once and reuse many times statement? If yes, why need to close it each time?

我知道调用 close() 会释放资源.但是如果我们知道以后要使用它,为什么要释放它,然后再请求它?

I know the call to close() will release the resource. But If we know we are going to use it later, why release it and then request it again later?

多客户端应用程序怎么样?我们需要一个连接池,所以我们每次都需要创建和关闭 Connection、StatementPreparedStatement?

How about a multi-client application? We need a connection pool and so we need to create and close Connection, Statement, and PreparedStatement each time?

谢谢.

推荐答案

就我个人而言,我会使用池,因为这将为您处理所有资源管理.如果您的连接要求发生变化,那么您可以轻松修改池配置.使用池后,您可以根据最佳实践打开/关闭连接和准备好的语句并将资源管理留给池.

Personally I'd use a pool as this will take care of all of the resource management for you. If your connection requirements change then you can easily modify the pool configuration. With a pool in place you can open/close connections and prepared statements according to best-practice and leave the resource management to the pool.

通常,当使用池时:

  • 关闭连接实际上只是将它返回到池中
  • 准备语句的行为将从 Connection 的语句缓存中检索先前准备好的语句,或者如果一个语句不可用,则创建一个新语句并将其缓存以备后用.
  • 关闭 PreparedStatement 的行为实际上只是将其返回到连接的语句缓存中.

此外 - 取决于池的实现 - 它可能能够在出现资源泄漏时通知您,从而更容易识别代码中的此类问题.

Furthermore - depending on the pool implementation - it may be able to notify you when there are resource leaks making it easier to identify these sorts of problems in your code.

查看一个示例实现的源代码,例如 DBCP - 看看如何他们工作.

Take a look at the source of an example implementation like DBCP - it's quite interesting to see how they work.

这篇关于何时关闭 JDBC 中的 Connection、Statement、PreparedStatement 和 ResultSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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