Java连接多个数据库

发布于 2024-12-21 03:21:47 字数 2094 浏览 3 评论 0原文

我正在创建一个连接到多个数据库的java应用程序。用户将能够从下拉框中选择他们想要连接的数据库。

然后,程序通过将名称传递给创建初始上下文的方法来连接到数据库,以便它可以与 Oracle Web 逻辑数据源进行通信。

public class dbMainConnection {

    private static dbMainConnection conn = null;
    private static java.sql.Connection dbConn = null;
    private static javax.sql.DataSource ds = null;
    private static Logger log = LoggerUtil.getLogger();

    private dbMainConnection(String database) {

         try {

            Context ctx = new InitialContext();

            if (ctx == null) {
                log.info("JDNI Problem, cannot get InitialContext");
            }

                database = "jdbc/" + database;
                log.info("This is the database string in DBMainConnection" + database);
                ds = (javax.sql.DataSource) ctx.lookup (database);


        } catch (Exception ex) {
            log.error("eMTSLogin: Error in dbMainConnection while connecting to the database : " + database, ex);
        }

    }

    public Connection getConnection() {

        try {

            return ds.getConnection();

        } catch (Exception ex) {
            log.error("Error in main getConnection while connecting to the database : ", ex);
            return null;
        }

    }

    public static dbMainConnection getInstance(String database) {

        if (dbConn == null) {
            conn = new dbMainConnection(database);
        }

        return conn;

    }

    public void freeConnection(Connection c) {
        try {
            c.close();
            log.info(c + "  is now closed");
        } catch (SQLException sqle) {
            log.error("Error in main freeConnection : ", sqle);
        }
    }

}

我的问题是,如果有人忘记为数据库创建数据源,但他们仍然将其添加到下拉框中,会发生什么?现在发生的情况是,如果我尝试连接到没有数据源的数据库,则会错误提示无法获得连接。这就是我想要的,但是如果我首先连接到一个有数据源的数据库,这可以工作,然后尝试连接到没有数据源的数据库,它再次出现错误

javax.naming.NameNotFoundException:无法解析“jdbc.peterson”。解决了“jdbc”;剩下的名字是“彼得森”。

这又是我所期望的,但令我困惑的是,它随后获取了用于不同数据库的最后一个良好连接,并处理所有内容,就好像什么也没发生一样。

有人知道这是为什么吗? weblogic 是否缓存连接或作为故障安全措施?以这种方式建立联系是一个坏主意吗?

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 program then connects to the database by passing the name to a method that creates an initial context so it can talk with an oracle web logic data source.

public class dbMainConnection {

    private static dbMainConnection conn = null;
    private static java.sql.Connection dbConn = null;
    private static javax.sql.DataSource ds = null;
    private static Logger log = LoggerUtil.getLogger();

    private dbMainConnection(String database) {

         try {

            Context ctx = new InitialContext();

            if (ctx == null) {
                log.info("JDNI Problem, cannot get InitialContext");
            }

                database = "jdbc/" + database;
                log.info("This is the database string in DBMainConnection" + database);
                ds = (javax.sql.DataSource) ctx.lookup (database);


        } catch (Exception ex) {
            log.error("eMTSLogin: Error in dbMainConnection while connecting to the database : " + database, ex);
        }

    }

    public Connection getConnection() {

        try {

            return ds.getConnection();

        } catch (Exception ex) {
            log.error("Error in main getConnection while connecting to the database : ", ex);
            return null;
        }

    }

    public static dbMainConnection getInstance(String database) {

        if (dbConn == null) {
            conn = new dbMainConnection(database);
        }

        return conn;

    }

    public void freeConnection(Connection c) {
        try {
            c.close();
            log.info(c + "  is now closed");
        } catch (SQLException sqle) {
            log.error("Error in main freeConnection : ", sqle);
        }
    }

}

My problem is what happens if say someone forgets to create the data source for the database but they still add it to the drop down box? Right now what happens is if I try and connect to a database that doesn't have a data source it errors saying it cannot get a connection. Which is what I want but if I connect to a database that does have a data source first, which works, then try and connect to the database that doesn't have a data source, again it errors with

javax.naming.NameNotFoundException: Unable to resolve 'jdbc.peterson'. Resolved 'jdbc'; remaining name 'peterson'.

Which again I would expect but what is confusing me is it then grabs the last good connection which is for a different database and process everything as if nothing happened.

Anyone know why that is? Is weblogic caching the connection or something as a fail safe? Is it a bad idea to create connections this way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风来 2024-12-28 03:21:47

您将唯一的数据源(以及连接和 dbMainConnection)存储在类的静态变量中。每次有人请求数据源时,您都会用新的数据源替换前一个数据源。如果从 JNDI 获取数据源时发生异常,静态数据源将保持原样。您不应该在静态变量中存储任何内容。由于您的 dbMainConnection 类是使用数据库名称构造的,并且有多个数据库名称,因此将其设为单例是没有意义的。

只需使用以下代码来访问数据源:

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

让调用者从数据源获取连接,并在使用完毕后将其关闭。

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.

仙女 2024-12-28 03:21:47

您在查找不存在的数据源时捕获了 JNDI 异常,但您的单例仍然保留对先前查找的数据源的引用。正如 AB Cade 所说,在异常时甚至在此之前,对 ds 的引用为空。

更一般地说,也许使用 Singleton 并不是最好的主意。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文