Java connecting to multiple databases

前端 未结 2 1866
既然无缘
既然无缘 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:02

    You're catching JNDI exception upon lookup of the nonexistent datasource but your singleton still keeps the reference to previously looked up datasource. As A.B. Cade says, null reference to ds upon exception, or even before that.

    On a more general note, perhaps using Singleton is not the best idea.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题