Java oracle connect string

How to connect to Oracle using Service Name instead of SID

I have a Java application that uses JDBC (via JPA) that was connecting to a development database using hostname, port and Oracle SID, like this:

jdbc:oracle:thin:@oracle.hostserver1.mydomain.ca:1521:XYZ 

XYZ was the Oracle SID. Now I need to connect to a different Oracle database that does not use a SID, but uses an Oracle «Service Name» instead. I tried this but it doesn’t work:

jdbc:oracle:thin:@oracle.hostserver2.mydomain.ca:1522:ABCD 

8 Answers 8

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse’s answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED))) 

Can you incorporate the point about TNSNAMES format per answer from @Robert Greathouse to achieve answer perfection?

For me it didn’t work with the @, I had to use jdbc:oracle:thin://myhost:1521/myservicename, but also I didn’t provide user credentials

I’ve been trying to figure out how to connect to Oracle using JDBC thin driver on Google App Script and tried a number of syntax without success. jdbc:oracle:thin:USER/PWD@//my.ip.address:1521/SERVICENAME or jdbc:oracle:thin:@//my.ip.address.1521/SERVICENAME , with username and password as arguments to jdbc.getConnection() . Still puzzling.

So there are two easy ways to make this work. The solution posted by Bert F works fine if you don’t need to supply any other special Oracle-specific connection properties. The format for that is:

jdbc:oracle:thin:@//HOSTNAME:PORT/SERVICENAME 

However, if you need to supply other Oracle-specific connection properties then you need to use the long TNSNAMES style. I had to do this recently to enable Oracle shared connections (where the server does its own connection pooling). The TNS format is:

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

If you’re familiar with the Oracle TNSNAMES file format, then this should look familiar to you. If not then just Google it for the details.

Источник

Oracle® Database JDBC Java API Reference, Release 23c

The Oracle JDBC Driver supports the following URL formats.

EZConnect Format

In EZConnect format Hostname, Port and Service Name can be configured using a simple syntax.
Since 19c, the connection properties can be added at the end of the URL.
The syntax uses ‘?’ to indicate start of conection properties and ‘&’ as a delimiter between each property.

Syntax :

jdbc:oracle:thin:@[[protocol:]//]host1[,host2,host3][:port1][,host4:port2] [/service_name][:server_mode][/instance_name][?connection properties]

Examples:

  • jdbc:oracle:thin:@mydbhost:1521/mydbservice
  • jdbc:oracle:thin:@tcp://mydbhost:1521/mydbservice
  • jdbc:oracle:thin:@tcp://mydbhost1,mydbhost2:1521/mydbservice
  • jdbc:oracle:thin:@tcp://mydbhost1:5521,mydbhost2:1521/mydbservice
  • jdbc:oracle:thin:@tcp://mydbhost1:5521/mydbservice:dedicated
  • jdbc:oracle:thin:@mydbhost1:5521/mydbservice?oracle.net.httpsProxyHost=myproxy&oracle.net.httpsProxyPort=80
  • jdbc:oracle:thin:@tcps://mydbhost1:5521/mydbservice?wallet_location=/work/wallet
  • jdbc:oracle:thin:@tcps://mydbhost1:5521/mydbservice?wallet_location=/work/wallet&ssl_server_cert_dn=»Server DN»

TNS URL Format

This format is more structured way of specifying the connect options and more descriptive.

Syntax :

jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=) (HOST=)(PORT=)) (CONNECT_DATA=(SERVICE_NAME=))

Examples:

  • jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP) (HOST=mydbhost)(PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=mydbservice))
  • jdbc:oracle:thin:@(DESCRIPTION= (LOAD_BALANCE=on) (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521)) (ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=5221))) (CONNECT_DATA=(SERVICE_NAME=orcl)))
  • jdbc:oracle:thin:@(DESCRIPTION= (ADDRESS= (PROTOCOL=TCPS)(PORT=1522)(HOST=myhost)) (CONNECT_DATA=(SERVICE_NAME=dbservicename)) (SECURITY=(ssl_server_cert_dn=»CN=testcert.test.com, O=org,L=somecity,ST=state,C=US»)))

TNS Alias Format

To use the alias configured in the tnsnames.ora, use the below format. The location of the tnsnames.ora file can be configured using TNS_ADMIN parameter.

Syntax :

Examples:

This package is an Oracle JDBC extension that provides interfaces to access the Advanced Queuing feature of Oracle for enterprise messaging applications.

Beginning in Oracle Release 12.2, some of the Oracle extensions to JDBC are captured in the package oracle.jdbc.datasource .

This package holds data source and connection builder classes that implement the Oracle JDBC extension interfaces in the oracle.jdbc.datasource and oracle.jdbc packages.

This package is an Oracle JDBC extension that provides interfaces to access the Database Change Notification feature of Oracle.

Copyright © 2008, 2023, Oracle and/or its affiliates.

Источник

Подключение Connection

Для соединения с БД необходимо использовать класс Connection пакета java.sql. После установления соединения можно выполнять различные SQL-запросы и получать результаты их обработки сервером. Приложение может открыть одно или несколько соединений с одной или несколькими различными СУБД.

Открытие соединения, getConnection

Стандартный способ установления соединения — это вызов метода getConnection класса DriverManager. Методу getConnection необходимо передать строку URL (Uniform Resource Locator). Стандарт подключения к серверу базы данных позволяет использовать следующие методы getConnection с параметрами:

getConnection(url); getConnection(url, properties); getConnection(url, username, password);

При использовании первого варианта, все параметры подключения указываются в url.

В следующей таблице представлен JDBC driver и синтаксис строки URL для подключения к СУБД.

СУБД Драйвер JDBC URL
Oracle oracle.jdbc.OracleDriver jdbc:oracle:oci[OCI_VERSION]:@[HOST_NAME]
Oracle oracle.jdbc.OracleDriver jdbc:oracle:thin:@ [HOST_NAME]:[PORT_NUMBER]:[DATABASE_NAME]
MSSQL com.microsoft.jdbc.sqlserver.SQLServerDriver jdbc:microsoft:sqlserver: //[HOST_NAME]:[PORT_NUMBER]
PostgreSQL org.postgresql.Driver jdbc:postgresql: //[HOST_NAME]:[PORT_NUMBER] /[DATABASE_NAME]
MySQL com.mysql.jdbc.Driver jdbc:mysql://[HOST_NAME]:[PORT_NUMBER] /[DATABASE_NAME]

Подключение к СУБД Oracle, jdbc oracle

К серверу БД Oracle можно подключиться как через тонкий клиент, так и через толстый.

Пример подключения через тонкий клиент:

String host = "localhost"; int port = 1521 ; String sid = "SE" ; String user = "SCOTT" ; String pwd = "TIGER" ; try < Class.forName("oracle.jdbc.driver.OracleDriver"); >catch (ClassNotFoundException e) < System.out.println("Oracle JDBC Driver is not found"); e.printStackTrace(); exit (-1); >String url = String.format("jdbc:oracle:thin:@%s:%d:%s", host, port, sid); Connection connection = null; try < connection = DriverManager.getConnection(url, user, pwd); >catch (SQLException e) < System.out.println("Connection Failed : " + e.getMessage()); exit (-1); >if (connection != null) < System.out.println("You made it, take control your database now!"); >else < System.out.println("Failed to make connection!"); >connection.close();

При подключении через толстый клиент, host и port не указываются :

String sid = "SE" ; String user = "SCOTT" ; String pwd = "TIGER" ; . String url = String.format("jdbc:oracle:oci8:@%s", sid); Connection connection = null; try < connection = DriverManager.getConnection(url, user, pwd); >catch (SQLException e) < System.out.println("Connection Failed : " + e.getMessage()); >.

Подключение к СУБД MS SQL, jdbc sql

Строка URL-адреса подключения имеет следующий вид:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
  • jdbc:sqlserver:// — обязательно, подпротокол.
  • serverName — необязательно, адресом сервера, с которым выполняется соединение. Это может быть DNS, IP-адрес, локальный узел или 127.0.0.1 локального компьютера. Имя сервера необходимо указать в коллекции свойств, если оно не указано в URL-адресе соединения.
  • instanceName — необязательно, наименование базы данных сервера, с которым выполняется соединение. Подключение выполняется к базе данных по умолчанию, если не указана другая.
  • portNumber — необязательно, порт, который слушает сервер. Значение по умолчанию — 1433. Если соединение выполняется с портом по умолчанию, то в URL-адресе необязательно указывать порт.

Дополнительные свойства указывается в формате ключ=значение.

Примеры установления соединения с сервером БД

// Подключение к БД по умолчанию на localhost: jdbc:sqlserver://localhost;user=userName;password=*****; // Подключение к БД по умолчанию наlocalhost со встроенной проверкой безопасности: jdbc:sqlserver://localhost;integratedSecurity=true; // Подключение к именованной БД: jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true; // Подключение к именованной БД с использованием порта по умолчанию: jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks;integratedSecurity=true; // Подключение к именованной БД с указанием настраиваемого имени приложения: jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;applicationName=MyApp;

Подключение к СУБД PostgreSQL, jdbc postgresql

Для подключения к серверу БД PostgreSQL необходимо использовать один из следующих URL:

jdbc:postgresql:database jdbc:postgresql://host/database jdbc:postgresql://host:port/database jdbc:postgresql://host:port

host — имя сервера, по умолчанию «localhost».

port — порт, который слушает сервер. По умолчанию используется порт 5432.

database — наименование базы данных. По умолчанию используется база данных postgres.

Примеры jdbc postgresql :

String url1 = "jdbc:postgresql://localhost/test?user=postgres&password=secret&ssl=true"; String url2 = "jdbc:postgresql://localhost/test"; String user = "postgres"; String pwd = "secret"; Properties props = new Properties (); props.setProperty("user" , user ); props.setProperty("password", pwd ); props.setProperty("ssl" ,"true"); Connection connection1 = DriverManager.getConnection(url1); Connection connection2 = DriverManager.getConnection(url2, props); Connection connection3 = DriverManager.getConnection(url2, user, pwd);

Подключение к СУБД MySQL, jdbc mysql

String driver = «com.mysql.jdbc.Driver»; String url = «jdbc:mysql://localhost:3306/»; String dbName = «. «; String userName = «. «; String password = «. «; try < Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url + dbName, userName, password); if (conn != null) System.out.println ("Приложение подключилось к БД !"); else System.out.println ("Приложение НЕ подключилось к БД ?"); conn.close(); >catch (Exception e)

Пример динамической загрузки JDBC-драйвера и подключение к серверу рассмотрен здесь.

Источник

Читайте также:  Java main args integer
Оцените статью