How to connect to Oracle using Service Name instead of SID
To connect to an Oracle database using a service name instead of a SID (System Identifier), you can use the thin driver and specify the connection URL in the following format:
To connect to an Oracle database using a service name instead of a SID (System Identifier), you can use the thin driver and specify the connection URL in the following format:
jdbc:oracle:thin:@<host>:<port>:<service_name>For example:
jdbc:oracle:thin:@localhost:1521:orclThis connection URL specifies the thin driver, the host name (localhost), the port number (1521), and the service name (orcl).
To connect to the database, you can use the DriverManager.getConnection() method and pass it the connection URL, the user name, and the password as arguments.
Here is an example of how to connect to an Oracle database using a service name:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "user";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Use the connection here
} catch (SQLException e) {
// Handle the SQL exception
}
}
}This code establishes a connection to the Oracle database using the provided URL, username, and password. Note that modern JDBC (4.0+) automatically registers the driver, so explicit loading is no longer required.
Before running this code, ensure the Oracle JDBC driver is included in your project dependencies. For Maven, add the following to your pom.xml:
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>21.9.0.0</version>
</dependency>