MySQL (Java) 的单例连接模式的关闭连接
Close connection for singleton connection pattern for MySQL (Java)
我想知道我的 DBConnecter class 中是否需要 closeConnection() 方法。我知道您通常会在使用完连接后关闭连接,但由于连接是单例连接,我不完全确定。
这是我的 DBConnecter class:
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;
}
这可能没什么大不了的,但我想确定一下,因为这是学校的考试项目(:
打开与数据库的连接是一个昂贵的过程。由于您使用的是单例并假设您的所有数据库交互都由该对象处理,因此我建议保持连接处于活动状态。但是,您需要在退出应用程序之前关闭连接。
如果您希望同时发生许多查询,您可能需要查看连接池,但是由于这是一个学校项目,我认为情况并非如此。
我想知道我的 DBConnecter class 中是否需要 closeConnection() 方法。我知道您通常会在使用完连接后关闭连接,但由于连接是单例连接,我不完全确定。
这是我的 DBConnecter class:
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;
}
这可能没什么大不了的,但我想确定一下,因为这是学校的考试项目(:
打开与数据库的连接是一个昂贵的过程。由于您使用的是单例并假设您的所有数据库交互都由该对象处理,因此我建议保持连接处于活动状态。但是,您需要在退出应用程序之前关闭连接。
如果您希望同时发生许多查询,您可能需要查看连接池,但是由于这是一个学校项目,我认为情况并非如此。