数据库连接应始终保持打开状态还是仅在需要时打开?

数据库连接应始终保持打开状态还是仅在需要时打开?

问题描述:

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

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

请原谅noob问题,但是数据库连接应该一直保持打开状态,还是在需要时打开和关闭?

Pardon the noob question, but 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
    


  • 但由于手动打开数据库连接太昂贵,强烈建议使用数据库连接池。这将为您处理物理数据库连接,当您关闭它(即调用 Connection #close )时,物理数据库连接将在睡眠模式仍然开启。

    But since manually opening a database connection is too expensive, it is highly recommended to use a database connection pool. 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.

    相关问答:


    • Java连接池

    • Java Connection Pooling

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

    Some tools to handle database connection pooling:

    • BoneCP
    • c3po
    • Apache Commons DBCP
    • HikariCP