【问题标题】:Storing Connection String in a String将连接字符串存储在字符串中
【发布时间】:2013-07-20 11:06:08
【问题描述】:

如何存储我的连接字符串 例如:"jdbc:oracle:thin:@local:testserver","scott","tiger" 在 String 变量中并将该字符串传递给连接?

【问题讨论】:

    标签: java database string connection-string


    【解决方案1】:

    怎么样

    String connString = "jdbc:oracle:thin:@local:testserver";
    

    将其传递给您的连接:

    Connection conn = DriverManager.getConnection(connString,"someUsername","somePassword");
    

    有一个使用Java连接oracle数据库的教程here

    【讨论】:

    • @Asif 究竟是什么不起作用?如果您只是说“它不工作”,就很难判断出了什么问题
    • 对不起 :) 非常感谢。我忘记了逗号。
    【解决方案2】:

    瘦名称服务语法:http://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

    如果您需要提供其他特定于 Oracle 的连接属性,那么您需要使用长 TNSNAMES 样式。 TNS 格式为:

    jdbc:oracle:thin:@(description=(address=(host=HOSTNAME)(protocol=tcp)(port=PORT))(connect_data=(service_name=SERVICENAME)(server=SHARED)))

    【讨论】:

      【解决方案3】:

      你可以像这样实例化一个字符串:

      String connectionString = "jdbc:oracle:thin:@local:server";
      

      然后使用这个字符串进行连接,就像 Thousand 写的那样。

      无论如何,我认为这段代码不能重复使用。最好像这样创建一个类连接:

      import java.sql.Connection;
      import java.sql.DriverManager;
      
      public class ConectionTest {
      
          static Connection getConnection() throws Exception {
      
              String connectionString = "jdbc:oracle:thin:@local:server";
              String driver = "com.mysql.jdbc.Driver";
              String userName = "usertest";
              String password = "pwdtest";
      
              Class.forName(driver).newInstance();
              Connection conn = DriverManager.getConnection(connectionString, userName,password);
      
              return conn;
          }
      }
      

      然后在任何地方使用连接。

      【讨论】:

        猜你喜欢
        • 2011-08-11
        • 1970-01-01
        • 1970-01-01
        • 2015-12-02
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        相关资源
        最近更新 更多