是有一个永远开放的联系更好,还是每次有需要的时候都建立联系更好?



目前,我的程序每次需要时都要与服务器建立连接,并在获取所需内容后关闭连接。

Connection con = DriverManager.getConnection(url, user, pass);      
//grab data      
con.close();

这是更好还是更坏的做法,如果我从程序开始就只运行一个全局连接,它会有什么不同?比如

public static Connection con = DriverManager.getConnection(url, user, pass);

然后引用到我需要的地方比如

classname.con.createStatement();

这取决于您的应用程序。您应该按照自己的需要编写代码——然而,大型应用程序的一个会话可能会带来问题。

例如线程安全。如果多个用户连接到您的应用程序,则一个会话/连接超出范围。

我将为每个请求使用一个连接——附带一个额外的连接池和最大打开连接数。

并且因为使用连接可以抛出异常,所以将您的代码放入try-with-resources块中,然后您的连接将自动关闭。

try (Connection con = DriverManager.getConnection(myConnectionURL);) {
    // grab data
} catch (SQLException e) {
    e.printStackTrace();
}

您应该遵循单例设计模式来连接数据库,下面是数据库连接的单例设计模式的示例

 /**
     * Singleton for connecting to a database through JDBC
     * 
     *
     **/
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class JDBC {
        private static Connection connection = null;
        private final static String ADRESS   = "";
        private final static String DATABASE = "";
        private final static String USER     = "";
        private final static String PASSWORD = "";
        private final static String PORT     = "";
        private final static String DRIVER   = "";
        /**
         * Method that loads the specified driver
         * 
         * @return void
         **/
        private static void loadDriver() {
            try {
                Class.forName(DRIVER);
            }
            catch (Exception e) {
                errorHandler("Failed to load the driver " + DRIVER, e);
            }
        }
        /**
         * Method that loads the connection into the right property
         * 
         * @return void
         **/
        private static void loadConnection() {
            try {
                connection = DriverManager.getConnection(getFormatedUrl(), USER, PASSWORD);
            }
            catch (SQLException e) {
                errorHandler("Failed to connect to the database " + getFormatedUrl(), e);         
            }
        }
        /**
         * Method that shows the errors thrown by the singleton
         * 
         * @param  {String}    Message
         * @option {Exception} e
         * @return  void
         **/
        private static void errorHandler(String message, Exception e) {
            System.out.println(message);  
            if (e != null) System.out.println(e.getMessage());   
        }
        /**
         * Method that returns the formated URL to connect to the database
         * 
         * @return {String}
         **/
        private static String getFormatedUrl() {
            return ADRESS + ":" + PORT + "/" + DATABASE;
        }
        /**
         * Static method that returns the instance for the singleton
         * 
         * @return {Connection} connection
         **/
        public static Connection getConnection() {
            if (connection == null) {
                loadDriver();
                loadConnection();
            }
            return connection;
        }
        /**
         * Static method that close the connection to the database
         * 
         * @return void
         **/
        public static void closeConnection() {
            if (connection == null) {
                errorHandler("No connection found", null);
            }
            else {
                try {
                    connection.close();
                    connection = null;
                }
                catch (SQLException e) {
                    errorHandler("Failed to close the connection", e);
                }
            }
        }
    }

最新更新