数据库连接应该一直保持打开状态还是只在需要时才打开? [英] Should a database connection stay open all the time or only be opened when needed?

查看:35
本文介绍了数据库连接应该一直保持打开状态还是只在需要时才打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要连接到数据库的 bukkit 插件 (minecraft).

I have a bukkit plugin (minecraft) that requires a connection to the database.

数据库连接应该一直保持打开状态,还是在需要时打开和关闭?

Should a database connection stay open all the time, or be opened and closed when needed?

推荐答案

数据库连接必须仅在需要时打开,并在完成所有必要的工作后关闭.代码示例:

The database connection must be opened only when its needed and closed after doing all the necessary job with it. Code sample:

  • Java 7 之前:

  • Prior to Java 7:

  Connection con = null;
  try {
      con = ... //retrieve the database connection
      //do your work...
  } catch (SQLException e) {
      //handle the exception
  } finally {
      try {
          if (con != null) {
              con.close();
          }
      } catch (SQLException shouldNotHandleMe) {
          //...
      }
  }

  • Java 7:

  • Java 7:

      try (Connection con = ...) {
      } catch (SQLException e) {
      }
      //no need to call Connection#close since now Connection interface extends Autocloseable
    

  • 但是由于手动打开数据库连接成本太高,强烈建议使用数据库连接池,用Java表示,DataSource 接口.这将为您处理物理数据库连接,当您关闭它(即调用Connection#close)时,物理数据库连接将只是处于睡眠模式并且仍处于打开状态.

    But since manually opening a database connection is too expensive, it is highly recommended to use a database connection pool, represented in Java with DataSource interface. This will handle the physical database connections for you and when you close it (i.e. calling Connection#close), the physical database connection will just be in SLEEP mode and still be open.

    相关问答:

    一些处理数据库连接池的工具:

    Some tools to handle database connection pooling:

    这篇关于数据库连接应该一直保持打开状态还是只在需要时才打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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