Search code examples
javadatabaseoracle-databasejdbc

Oracle Database JDBC connection using datasource


I am connecting to oracle database via datasource , as all know we have two types of connection one using sid and another using service name . For Service name connection

        OracleDataSource dataSource = new OracleDataSource();
        dataSource.setDriverType("thin");
        dataSource.setServerName(hostname);
        dataSource.setPortNumber(Integer.parseInt(port));
        dataSource.setServiceName(serviceName);
        dataSource.setUser(username);
        dataSource.setPassword(password);

This works perfectly fine but in this case if i want to establish a connection using sid There is no method called setSid() or anything like that Is there any way or should I use

      String url = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + sid;
      dataSource.setUrl(url);
      dataSource.setUser(username);
      dataSource.setPassword(password);

Is my approach correct or am i missing something JDBC doc for reference https://docs.oracle.com/en/database/oracle/oracle-database/19/jajdb/oracle/jdbc/pool/OracleDataSource.html


Solution

  • It looks like from the documentation, you would use .setDatabaseName(sid) but I don't have an Oracle database to test against.

          String url = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + sid;
          dataSource.setUrl(url);
          dataSource.setUser(username);
          dataSource.setPassword(password);
          dataSource.setDatabaseName(sid);
    

    ref: https://docs.oracle.com/en/database/oracle/oracle-database/19/jajdb/oracle/jdbc/pool/OracleDataSource.html#setDatabaseName_java_lang_String_

    Set the name of a particular database on a server. In Oracle's jargon this is called SID (System Identifier).