【问题标题】:How to save Oracle connection string to variable in Java [closed]如何将Oracle连接字符串保存到Java中的变量[关闭]
【发布时间】:2017-10-19 20:42:38
【问题描述】:

我可以在 DriverManager.getConnection 参数中使用一个变量来使其动态化吗?

    String connstring = null;       
    Connection conn = null;
    try {
        conn = DriverManager.getConnection                 
               ("jdbc:oracle:thin:@hostname:port:sid","uname","pword");                             
               //(connstring);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但是,当我尝试将连接字符串封装到如下代码的变量时。我收到“调用中的参数无效”。

    String connstring = null;       
    connstring = "\"jdbc:oracle:thin:" + host + ":" + port + ":" + sid + "\"" + "," + "\"" + uname + "\"" + "," + "\"" + pword + "\"";
    System.out.println(connstring);
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(connstring);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我打印出变量,它与第一种方法的引号完全一样。

我还尝试了一种不同的方法,如下所示。这次我收到“指定的 Oracle URL 无效”。

    Connection con = null;

    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        con = DriverManager.getConnection(dbaseurl, dbaseuser, dbasepwrd);
        //con.setAutoCommit(false);
    } catch (ClassNotFoundException e) {
        System.out.println("Oracle JDBC Driver Missing");
        e.printStackTrace();
        return null;
    } catch (SQLException e) {
        System.out.println("Connection could not be obtained.");
        e.printStackTrace();
        return null;
    }

我研究了 10g 的 oracle url,它似乎是有序的。下面是我如何初始化 dbaseurl 变量。目标不是硬编码连接属性。请帮忙。谢谢。

"jdbc:oracle:thin@hostname:port"

【问题讨论】:

    标签: java oracle database-connection connection-string


    【解决方案1】:

    您似乎从以前的代码中创建了一个字符串,包括", 字符。

    【讨论】:

    • 好的。基于此,将连接字符串放在变量中,然后从 get 连接中调用它是不可行的。但是,我也尝试过这种方法,但仍然无法正常工作
    • conn = DriverManager.getConnection ("\"jdbc:oracle:thin:\"" + host + ":" + port + ":" + sid + "\"" + ",\" " + uname + "\"," + "\"" + pword + "\"");
    • 如果将这些值设置为 a,b,c...,则该字符串的值为:"jdbc:oracle:thin:"a:b:c","d","e"。即,它包含", 字符。这些不应该在您的连接字符串中。
    【解决方案2】:

    可能只需要一些提示。但这有效。而不是一根弦。我将每个参数保存到一个变量中。

        String dburl = "jdbc:oracle:thin:" + host + ":" + port + ":" + sid;
        System.out.println(dburl);
    
        Connection conn = null;
        try {
            conn = DriverManager.getConnection
                   //("\"jdbc:oracle:thin:\"" + host + ":" + port + ":" + sid + "\"" + ",\"" + uname + "\"," + "\"" + pword + "\"");
    
                    (dburl,uname,pword);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      相关资源
      最近更新 更多