Ora 12505 ошибка

Есть несколько вещей, которые могут вызвать эту проблему, но прежде чем вы начнете работу с JDBC, вы должны быть уверены, что можете подключиться к базе данных с помощью SQL * Plus. Если вы не знакомы с SQL * Plus, это инструмент командной строки для подключения к базам данных Oracle, который долгое время являлся стандартной частью Oracle и включен в Oracle XE.

При подключении к базе данных Oracle с помощью JDBC вы не подключаетесь непосредственно к базе данных. Вместо этого вы подключаетесь к слушателю TNS, который затем соединяет вас с базой данных. Ошибка ORA-12505 означает, что слушатель встал и вы могли подключиться к нему, но он не смог подключить вас к базе данных, потому что он не знает, что эта база данных. Для этого есть две причины:

  • база данных не запущена,
  • база данных не была зарегистрирована у слушателя, например. потому что база данных была запущена перед слушателем. (Когда база данных начинается, она регистрируется при прослушивании, если она уже запущена. Если слушатель не запущен, база данных не регистрируется, и если слушатель запускается, он не ищет базы данных, которые могут зарегистрируйтесь в нем.)

ORA-12505 означает, что слушатель знает об этой базе данных, но слушатель не получил уведомление из базы данных, что база данных. (Если вы пытались подключиться к неправильной базе данных, используя неправильный идентификатор SID, вы получили бы ошибку ORA-12154 «TNS: не удалось разрешить указанный идентификатор подключения».)

Какие службы Oracle работают в оснастке «Службы»? (Откройте это из панели управления > «Администрирование» > «Службы» или просто «Пуск» > «Выполнить» > services.msc.) Вам нужны службы OracleServiceXE и OracleXETNSListener для запуска.

Если службы были запущены, можете ли вы подключиться к базе данных в SQL * Plus, используя любое из приведенных ниже команд в командной строке? (Я предполагаю, что вы запускаете их на машине, на которой установлен Oracle XE.)

sqlplus system/system-password@XE
sqlplus system/system-password
sqlplus / as sysdba

(Замените system-password паролем, который вы установили для пользователей SYS и SYSTEM во время установки Oracle XE.)

Первый из этих трех подключается через прослушиватель TNS, а второй два напрямую подключаются к базе данных, не проходя через прослушиватель, и работают только в том случае, если вы находитесь на том же компьютере, что и база данных. Если первый не удастся, но два других успеха, то соединения JDBC также потерпят неудачу. Если это так, подключитесь к базе данных с помощью одного из двух других и запустите ALTER SYSTEM REGISTER. Затем выйдите из SQL * Plus и снова попробуйте первую форму.

Если третий не работает, а второй работает, добавьте свою учетную запись в группу ora_dba. Сделайте это в панели управления > Управление компьютером > Локальные пользователи и группы.

Как только вы сможете получить соединения формы

sqlplus system/system-password@XE

вы должны иметь возможность подключаться к Oracle XE через JDBC. (Кстати, вы не указали нам код JDBC, который вы используете для подключения к базе данных, но я бы предположил, что он, скорее всего, правильный, будут другие другие ошибки, если части строки соединения были неправильными.)

There are a few things that can cause this problem, but before you get started with JDBC, you need to be sure that you can connect to the database using SQL*Plus. If you’re not familiar with SQL*Plus, it’s a command-line tool for connecting to Oracle databases that has been a standard part of Oracle for a long time and it is included with Oracle XE.

When connecting to an Oracle database using JDBC, you don’t connect to the database directly. Instead, you connect to a TNS listener, which then connects you to the database. The error ORA-12505 means that the listener was up and you could connect to it, but it couldn’t connect you to the database because it doesn’t know that that database is up. There are two reasons for this:

  • the database has not been started up,
  • the database has not registered with the listener, e.g. because the database was started before the listener. (When the database starts, it registers itself with a listener if it is already running. If the listener isn’t running, the database doesn’t register itself, and if the listener starts, it doesn’t go looking for databases that might register with it.)

ORA-12505 means that the listener knows about that database, but the listener hasn’t received a notification from the database that the database is up. (If you were trying to connect to the wrong database, using the wrong SID, you would get an ORA-12154 error «TNS: could not resolve the connect identifier specified».)

What Oracle services are running in the Services snap-in? (Open this from Control Panel > Administrative Tools > Services, or just Start > Run > services.msc.) You need the services OracleServiceXE and OracleXETNSListener to be running.

If the services have both been started, can you connect to the database in SQL*Plus using any of the following at a command prompt? (I’m assuming you’re running these on the machine you’ve installed Oracle XE on.)

sqlplus system/system-password@XE
sqlplus system/system-password
sqlplus / as sysdba

(Replace system-password with the password you set for the SYS and SYSTEM users during the Oracle XE installation.)

The first of these three connect via the TNS listener, but the second two connect directly to the database without going via the listener, and only work if you’re on the same machine as the database. If the first one fails but the other two succeed, then JDBC connections will also fail. If so, connect to the database using either of the other two and run ALTER SYSTEM REGISTER. Then exit from SQL*Plus and try the first form again.

If the third one fails but the second one works, add your user account to the ora_dba group. Do this in Control Panel > Computer Management > Local Users and Groups.

Once you can get connections of the form

sqlplus system/system-password@XE

to work, you ought to be able to connect to Oracle XE via JDBC. (Incidentally, you haven’t shown us the JDBC code you’re using to connect to the database, but I would suspect that it is quite probably correct; there would be various other errors if parts of the connection string were wrong.)

ORA-12505 means that the SID you provided in the connect identifier does not match any SID registered with the listener. Basically, SID means $ORACLE_SID, which is the instance name by default.

SID in TNSNAMES.ORA

In some upgrade or migration cases, some users used to use SID to connect to the old database. The connect identifier in TNSNAMES.ORA may look like this:

ERP2 =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.153)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SID = ERP2)
      (SERVER = DEDICATED)
    )
  )

When they connect to the new database which may be a pluggable database (PDB), they’re unable to connect to the database with the same connect identifier. This is because the new database adopts SERVICE_NAME instead of SID as the entry point of connection.

C:\Users\edchen>sqlplus hr/hr@erp2
...
ERROR:
ORA-12505: TNS:listener does not currently know of SID given in connect descriptor

We saw the connection failed with ORA-12505.

Solutions to ORA-12505

In fact, in a multitenant environment, the used name of SID has become a service name belonging to the migrated DB or PDB. SID is no longer used. That’s why the listener refused to establish connections, because there’s no such SID registered with the listener.

There’re two types of solution that you can choose.

  1. Use SERVICE_NAME on Client Side
  2. Use SID as SERVICE_NAME on Server-Side

1. Use SERVICE_NAME on Client Side

SERVICE_NAME in TNSNAMES.ORA

You can change the content of every client’s connect identifier from SID into SERVICE_NAME in TNSNAMES.ORA.

ERP2 =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.153)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = ERP2)
      (SERVER = DEDICATED)
    )
  )

But where we can find TNSNAMES.ORA file? You may take a look.

Without TNSNAMES.ORA

At times, you may not able to modify TNSNAMES.ORA. In such moment, you can still connect to the database without TNSNAMES.ORA.

SERVICE_NAME in JDBC

For JDBC programmers, you can change the connect string from:

<IP Address>:<Port Number>:<SID>
Ex.
192.168.0.153:1521:ERP2

Into this:

//<IP Address>:<Port Number>/<Service_Name>
Ex.
//192.168.0.153:1521/ERP2

The differences are:

  • Leading by double slashes.
  • Delimited by a single slash between port number and service name.
  • The SID is replaced with the service name.

This should be able to prevent ORA-12505, and after this, I know you may see some other errors like ORA-28040 or ORA-01017 if you connect to the database from a plain old client version, e.g. Oracle 9i client.

2. Use SID as SERVICE_NAME on Server-Side

If you prefer to solve this issue on the server side, the potential solution is to make the listener treat the SID as SERVICE_NAME and establish connections for users. Luckily, Oracle provides a parameter USE_SID_AS_SERVICE_LISTENER for listener to do this.

USE_SID_AS_SERVICE_<Listener Name> = ON

For Single-instance DB

In our case, we add this feature to listener.ora.

[oracle@test ~]$ vi $ORACLE_HOME/network/admin/listener.ora
...
USE_SID_AS_SERVICE_LISTENER = ON

Then we restart the listener to make it work.

[oracle@test ~]$ lsnrctl stop
[oracle@test ~]$ lsnrctl start

For RAC DB

For cluster databases, we should go for listener.ora at grid-level on ALL nodes.

[grid@primary01 ~]$ vi $ORACLE_HOME/network/admin/listener.ora
...
USE_SID_AS_SERVICE_LISTENER = ON

Then restart listeners on all nodes.

[grid@primary01 ~]$ srvctl stop listener
[grid@primary01 ~]$ srvctl start listener
[grid@primary01 ~]$ srvctl status listener
Listener LISTENER is enabled
Listener LISTENER is running on node(s): primary02,primary01

Restrictions

Please note that, such backward compatibility has some restrictions. For a cluster system, USE_SID_AS_SERVICE_LISTENER is only used for connecting databases directly through local listeners.

Which means, SCAN listener won’t translate SID into SERVICE_NAME, so don’t use SCAN IP, use public or virtual IP of specific node.

In other words, if you insist on using SCAN IP to connect to the database, you should change SID into SERVICE_NAME in your connection string.

3. Test Connection

Now we can test the connection again.

C:\Users\edchen>sqlplus hr/hr@erp2
...
Connected to:
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> show user
USER is "HR"

In practice, SID is usually used to register as a static service in the listener.

If you don’t see any error pattern of your case in this post, please check: How to Resolve ORA-12514: TNS:listener does not currently know of service requested in connect descriptor. There’re more patterns of connection problems.

This error is received when the listener received a request to establish a connection to a database or other service but the connect descriptor received by the listener specified a SID for an instance (usually a database instance) that either has not yet dynamically registered with the listener or has not been statically configured for the listener therefore listener is not aware of the SID.

In Listener Static Registration the SID is mentioned in the listener.ora by which listener knows about the SID.

#Here orcl is the SID name which is registered in the listener.ora 

LISTENER=
(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=tcp)(HOST=myserver.example.com)(PORT=1521))
(ADDRESS=(PROTOCOL=ipc)(KEY=extproc))))
SID_LIST_LISTENER=
(SID_LIST=
(SID_DESC=
(SID_NAME=orcl))

In Listener Dynamic Registration, SID is not mentioned in listener.ora instead its the job of PMON process to register the database to the listener and then the listener is made aware of the SID.

By default, the PMON process contact the listener running on port 1521 to perform the registration. To instruct PMON process to register to a listener running on different port, we have to change the LOCAL_LISTENER parameter. Since its dynamic LOCAL_LISTENER parameter can simply be altered using ALTER SYSTEM command.

#Following command will set local_listener to port 1522
alter system set local_listener='(ADDRESS = (PROTOCOL=TCP)(HOST=localhost.localdomain)(PORT=1522))';

#Following command will instruct PMON to register the SID on the listener defined by local_listener parameter
alter system register;

If the SID is registered with the listener, it should show the SID in the Services summary:-

> lsnrctl status
LSNRCTL for Linux: Version 11.2.0.4.0 - Production on 21-DEC-2018 14:17:04
Copyright (c) 1991, 2013, Oracle. All rights reserved.
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=ISM01)))
STATUS of the LISTENER
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.4.0 - Production
Start Date 10-AUG-2018 13:01:12
Uptime 133 days 2 hr. 15 min. 51 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /apps/network/admin/listener.ora
Listener Log File /apps/network/admin/listener.log
Listening Endpoints Summary…
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=orcl)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost.localdomain)(PORT=1522)))
Services Summary…
Service "orcl" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this service…

The command completed successfully

If the service summary in lsnrctl status does not show the SID given in the client’s tnsnames.ora (CONNECT_DATA) then ensure that the same SID is either dynamically or statically registered with the listener.

Related posts

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor error occurs when the listener cannot find any matched SID with the provided SID, preventing it from connecting to the database.The database connection Sid you used is either unavailable or wrongly configured. Oracle Listener discovers a discrepancy between your Sid and the connection descriptor settings. The error ORA-12505, TNS:listener does not currently know of SID given in connect descriptor is thrown when oracle fails to create a connection due to invalid SID provided in the configuration.

Please wait a moment while the Oracle service starts up before attempting to connect again. Run the command lsnrctl services to see what services the listener already has. Verify that the service specified by the SID parameter in the connect descriptor of the net SID used is one that the listener is familiar with. If you used a connect identifier, ensure sure the SID is one that the listener recognises. To resolve the error ORA-12505, TNS:listener does not currently know of SID given in connect descriptor, look for any events in the listener.log file.

The Problem

You’ll be provided the host name, port, user name, password, and service name or Sid when you try to connect to a database. Oracle will wait for connections on the same host name and port when it starts up. The SID is the name of the presently running Oracle instance. The alias for the instance that lets you to connect to it is the service name. You will be unable to connect to the running Oracle database instance if the SID setting is incorrect.The error message ORA-12505, TNS:listener does not currently know of SID given in connect descriptor will be displayed.

Host name : localhost
port      : 1521
sid.      : orclcdb
username  : hr
password  : hr

Error

Status : Failure -Test failed: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
  (CONNECTION_ID=glCwDQzBSiScXNzmRhbuQg==)

Solution 1

It’s possible that the Oracle server is starting up. Retry the connection after a brief pause. It’s possible that a network outage will occur. This will prevent the connection to the Oracle database from being established. Make that the database is up and operating, and that there are no network issues with it. If you’re having trouble connecting to an Oracle database using the host name, consider using the IP address instead. Ensure that the port configuration and the operating port are same. If you’re connecting using an application, make sure the connection url follows the format.

jdbc:oracle:thin:@localhost:1521/sid

Solution 2

Check to see if the listen is working properly. You can pause and resume listening if there is a problem. The connection to the specified host and port will be refreshed as a result of this action. Multiple connections may cause the listener to hang. After restarting the listener, try connecting it again. The issue ORA-12514, TNS:listener does not presently know of service requested in connect descriptor, will be resolved as a result of this.

lsnrctl status

lsnrctl stop
lsnrctl start

Solution 3

Check to see if the specified SID corresponds to a valid SID in the Oracle database. The SQL statement below will query the Oracle database for the specified SID. Use the database’s SID if the SID specified in listener.ora varies from the database configuration. This will resolve the issue. ORA-12505: TNS:listener is unaware of the SID specified in the connect descriptor.

select value from v$parameter where name='service_names'

value
------
orclcdb

Solution 4

Check the listener.ora file for errors. This is how the configuration should appear. The SID LIST LISTENER will hold the Oracle instance settings. This setup will map GLOBAL DBNAME, SID NAME, and ORACLE HOME in the database. The service names from the preceding query should be the same as the SID NAME. The LISTENER setup determines the PROTOCAL, HOST, and PORT. This is how the LISTENER configuration waits for the database connection to establish.

/u01/app/oracle/product/version/db_1/network/admin/listener.ora

OR

[ORACLE_HOME]/network/admin/listener.ora

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = orclcdb)
      (SID_NAME = orclcdb)
      (ORACLE_HOME = /u01/app/oracle/product/version/db_1)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
    )
  )

#HOSTNAME by pluggable not working rstriction or configuration error.
DEFAULT_SERVICE_LISTENER = (orclcdb)

Solution 5

The SID settings, as well as the listener host and port, are all stored in the tnsnames.ora file. Below is an example tnsnames.ora file that demonstrates SID configuration. Check the SID in tnsnames.ora. Make the modifications specified below if the SID is not configured or is incorrectly configured.

/u01/app/oracle/product/version/db_1/network/admin/tnsnames.ora

OR

[ORACLE_HOME]/network/admin/tnsnames.ora

ORCLCDB=localhost:1521/orclcdb
ORCL=
 (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SID = orclcdb)
    )
  )

Solution 6

Check the oracle database’s system environment configuration. The proper database that is operating will be displayed in the Oracle database settings. It’s possible that numerous Oracle database versions are installed on the server, causing conflicts. Then /.bash profile, /.bashrc, or /etc/..bashrc will be used to set the environment.

export ORACLE_UNQNAME=orclcdb
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=$ORACLE_BASE/product/version/db_1
export ORACLE_SID=orclcdb
export PATH=/home/oracle/bin:/home/oracle/LDLIB:$ORACLE_HOME/bin:/usr/sbin:$PATH

Solution 7

Finally, while attempting to connect to the database, double-check the settings you gave. If you misspelt the configuration, an error message will appear. Check the configurations below to see whether they match your Oracle database configurations.

Host name : localhost
port      : 1521
sid       : orclcdb
username  : hr
password  : hr

Понравилась статья? Поделить с друзьями:
  • Ora 12012 ошибка при автоисполнение задания
  • Origin ошибка загрузки игры
  • Ora 06550 ошибка pls 00201
  • Origin ошибка 7049 12175
  • Ora 04063 ошибка