Java connecting to multiple databases

前端 未结 2 1867
既然无缘
既然无缘 2021-01-14 08:18

I am creating a java application that connects to multiple databases. A user will be able to select the database they want to connect to from a drop down box.

The p

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-14 09:11

    You're storing a unique datasource (and connection, and dbMainConnection) in a static variable of your class. Each time someone asks for a datasource, you replace the previous one by the new one. If an exception occurs while getting a datasource from JNDI, the static datasource stays as it is. You should not store anything in a static variable. Since your dbMainConnection class is constructed with the name of a database, and there are several database names, it makes no sense to make it a singleton.

    Just use the following code to access the datasource:

    public final class DataSourceUtil {
        /**
         * Private constructor to prevent unnecessary instantiations
         */
        private DataSourceUtil() {
        }
    
        public static DataSource getDataSource(String name) {
            try {
                Context ctx = new InitialContext();
                String database = "jdbc/" + name;
                return (javax.sql.DataSource) ctx.lookup (database);
            }
            catch (NamingException e) {
                throw new IllegalStateException("Error accessing JNDI and getting the database named " + name);
            }
        }
    }
    

    And let the callers get a connection from the datasource and close it when they have finished using it.

提交回复
热议问题