拥有一个始终打开的连接或者每次需要什么时更好地建立连接更好吗?

时间:2015-07-21 06:55:45

标签: java database postgresql coding-efficiency network-efficiency

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

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

如果我从程序开始只运行一个全局连接,那么它是更好还是更差的练习,它会有什么不同?像

这样的东西
public static Connection con = DriverManager.getConnection(url, user, pass);

只需用

之类的东西在我需要的地方引用它
classname.con.createStatement();

2 个答案:

答案 0 :(得分:0)

这取决于您的应用程序。你应该像你需要的那样编​​写代码 - 但是大型应用程序的一个会话可能会引入问题。

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

我会为每个请求使用一个连接 - 使用额外的连接池和最大量的打开连接。

因为使用连接会抛出异常,所以将代码放在try-with-resources块中,然后自动关闭连接。

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

答案 1 :(得分:-1)

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

 /**
     * 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);
                }
            }
        }
    }