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:


For example:


This 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 loads the thin driver, establishes a