Pattern for connecting to different databases using JDBC

后端 未结 4 1388
北荒
北荒 2021-02-09 07:33

I\'m writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.

Up till now I\'d been planning on using the

4条回答
  •  半阙折子戏
    2021-02-09 08:09

    I would suggest that you make it configurable and include the three drivers. You can use a pattern like this: Create a super class (lets call it DAO) that provides the functionality of connecting to the database. This could be abstract.

    Create a concrete sub class for each type of database that you wish to connect to. So you may end up with MySQLDAO, MSSQLDAO, and OracleDAO. each one will load the respective driver and use its respective connection string.

    Create another class (lets call it DAOFactory) with a method getDAO(DB) that will create an instance of the DAO depending on the value of DB.

    So for instance(in Pseudocode):

     if(DB.equals("MySQL")){
        DAO = new MySQLDAO();
    }
    return DAO;
    

    So any code that needs to connect to the database will call the DAOFactory and ask for a DAO instance. You may store the DB value in an external file (like a properties file) so that you do not have to modify code to change the type of database.

    this way your code does not need to know which type of database it is connecting to, and if you decide to support a fourth type of database later you will have to add one more class and modify the DAOFactory, not the rest of your code.

提交回复
热议问题