Java JDBC efficiency: How long should a connection be maintained?

后端 未结 4 1001
悲哀的现实
悲哀的现实 2021-02-10 01:37

I\'m still working on the same problem mention here. It seems to work fine especially after creating an AbstractModel class shown below:

public abstract class Ab         


        
4条回答
  •  广开言路
    2021-02-10 02:08

    Here is the Singleton Pattern which I initialize the myConenction field in all my Models to:

    public class DatabaseConnection {
        private static final String uname = "*******";
        private static final String pword = "*******";
        private static final String url = "*******************************";
    
        Connection connection;
        // load jdbc driver
        public DatabaseConnection(){
            try{
                Class.forName("org.postgresql.Driver");
                establishConnection();
            } catch (ClassNotFoundException ce) {
                System.out.println("Could not load jdbc Driver: ");
                ce.printStackTrace();
            }
        }
        public Connection establishConnection() {
            // TODO Auto-generated method stub
            try{
                connection = DriverManager.getConnection(url, uname, pword);
            } catch (SQLException e){
                System.out.println("Could not connect to database: ");
                e.printStackTrace();
            }
            return connection;
        }
    }
    
    public class SingletonConnection {
    
        private static DatabaseConnection con;
    
        public SingletonConnection(){}
    
        public static DatabaseConnection instance(){
    
            assert con == null;
                con = new DatabaseConnection();
            return con;
        }
    }
    

    Of course each and every connection to the database from the app goes through a Model.

提交回复
热议问题