MySQL(Java)单例连接模式的关闭连接

MySQL(Java)单例连接模式的关闭连接,java,mysql,database,connection,singleton,Java,Mysql,Database,Connection,Singleton,我想知道我的DBConnecter类中是否需要closeConnection()方法。我知道,你通常会关闭你的连接,每当你完成使用它,但由于连接是一个单一的,我不能完全肯定 以下是我的DBConnecter类: public static String driver = "com.mysql.jdbc.Driver"; public static String URL = "jdbc:mysql://localhost/polygondb"; public static String ID =

我想知道我的DBConnecter类中是否需要closeConnection()方法。我知道,你通常会关闭你的连接,每当你完成使用它,但由于连接是一个单一的,我不能完全肯定

以下是我的DBConnecter类:

public static String driver = "com.mysql.jdbc.Driver";
public static String URL = "jdbc:mysql://localhost/polygondb";
public static String ID = "root";
public static String PW = "root";
private static Connection connection = null;

public static Connection getConnection() {
    if (connection == null) {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            connection = DriverManager.getConnection(URL, ID, PW);
        } catch (SQLException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return connection;
}

这可能没什么大不了的,但我想确定一下,因为这是学校的考试项目(:

打开与数据库的连接是一个昂贵的过程。由于您使用的是单例,并且假设您的所有数据库交互都由该对象处理,我建议保持连接处于活动状态。但是,您需要在退出应用程序之前关闭连接


如果您希望同时出现许多查询,您可能希望查看连接池,但由于这是一个学校项目,我认为情况并非如此。

非常感谢您的快速回答!因此,当我有一个带有登录系统的应用程序时,我会在注销时断开连接?没问题。:)由于您的singleton正在处理与数据库的通信,因此您应该在启动程序时对其进行实例化,并且只在程序存在之前关闭连接。它应该通过用户登录和注销来保持。当一个用户注销时断开连接是没有意义的,因为另一个用户最终将登录在里面