Ora 12514 ошибка

null

ORA-12514 при подключении к экземпляру Oracle

Причин по которым может возникнуть ошибка ORA-12514 много, я расскажу об одной из возможных с предисторией.

У нашего заказчика развернут Oracle 11.2 на Windows Server.

При предоставлении заказчиком учётных данных для подключения нас насторожил обязательный формат логина SQLplus с явным указанием идентификатора соединения (connect_identifier)

sqlplus sys/pass@connect_identifier as sysdba

В процессе проведения работ нам потребовалось запустить базу данных в NOMOUNT через shutdown immediate,

C:\Windows\system32>sqlplus sys/pass@connect_identifier as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on ***

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Присоединен к:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> shutdown immediate
База данных закрыта.
База данных размонтирована.
Экземпляр ORACLE завершен.
SQL> startup nomount
ORA-12514: TNS:прослушиватель в данный момент не имеет данных о службе, запрашиваемой в дескрипторе соединения

Коннекция без идентификатора соединения не удавалась(а именно она позволила бы поднять базу).

Решение

Проблема заключалась в некорректном значении системной переменной ORACLE_SID, значение которой не соответствовало названию экземпляра. В корректно настроенной системе переменная значение ORACLE_SID должно соответсвовать названию экземпляра отображенному в названии сервиса OracleService%sid_name%.

Изменение системной переменной решило описанную проблему.

I had this issue and the fix was to make sure in tnsnames.ora the SERVICE_NAME is a valid service name in your database. To find out valid service names, you can use the following query in oracle:

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

Once I updated tnsnames.ora to:

TEST =
   (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = *<validhost>*)(PORT = *<validport>*))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = *<servicenamefromDB>*)
    )
)

then I ran:

sqlplus user@TEST

Success!
The listener is basically telling you that whatever service_name you are using isn’t a valid service according to the DB.

(*I was running sqlplus from Win7 client workstation to remote DB and blame the DBAs ;) *)

answered Apr 16, 2013 at 23:36

Brad Rippe's user avatar

Brad RippeBrad Rippe

3,4251 gold badge18 silver badges20 bronze badges

12

I know this is an old question, but still unanswered. It took me a day of research, but I found the simplest solution, at least in my case (Oracle 11.2 on Windows 2008 R2) and wanted to share.

The error, if looked at directly, indicates that the listener does not recognize the service name. But where does it keep service names? In %ORACLE_HOME%\NETWORK\ADMIN\listener.ora

The «SID_LIST» is just that, a list of SIDs and service names paired up in a format you can copy or lookup.

I added the problem Service Name, then in Windows «Services» control panel, I did a «Restart» on the Oracle listener service. Now all is well.


For example, your listener.ora file might initially look like:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

… And to make it recognize a service name of orcl, you might change it to:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
    (SID_DESC = 
        (GLOBAL_DBNAME = orcl)
        (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
        (SID_NAME = orcl)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

Kevin's user avatar

Kevin

75k12 gold badges134 silver badges166 bronze badges

answered Mar 25, 2014 at 12:13

Joseph Argenio's user avatar

3

In my circumstances the error was due to the fact the listener did not have the db’s service registered. I solved this by registering the services. Example:

My descriptor in tnsnames.ora:

LOCALDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = LOCALDB)
    )
  )

So, I proceed to register the service in the listener.ora manually:

SID_LIST_LISTENER =
    (SID_DESC =
      (GLOBAL_DBNAME = LOCALDB)
      (ORACLE_HOME = C:\Oracle\product\11.2.0\dbhome_1)
      (SID_NAME = LOCALDB)
    )

Finally, restart the listener by command:

> lsnrctl stop
> lsnrctl start

Done!

answered May 31, 2017 at 23:39

manix's user avatar

manixmanix

14.5k11 gold badges70 silver badges107 bronze badges

1

I had this issue at Windows server 2008 R2 and Oracle 11g

go to Net Manager > Listener > select database services form the combox > «Global Database Name» must be same as «SID» and «Oracle Home Directory» must be correct.

If you don’t have any entry for database services, create one and set correct global database , sid and oracle home.

Mr_and_Mrs_D's user avatar

Mr_and_Mrs_D

32.3k39 gold badges179 silver badges361 bronze badges

answered Dec 21, 2013 at 14:27

Sepideh's user avatar

SepidehSepideh

1491 silver badge2 bronze badges

1

This really should be a comment to Brad Rippe’s answer, but alas, not enough rep. That answer got me 90% of the way there. In my case, the installation and configuration of the databases put entries in the tnsnames.ora file for the databases I was running. First, I was able to connect to the database by setting the environment variables (Windows):

set ORACLE_SID=mydatabase
set ORACLE_HOME=C:\Oracle\product\11.2.0\dbhome_1

and then connecting using

sqlplus / as sysdba

Next, running the command from Brad Rippe’s answer:

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

showed that the names didn’t match exactly. The entries as created using Oracle’s Database Configuration Assistant were originally:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase.mydomain.com)
    )
  ) 

The service name from the query was just mydatabase rather than mydatabase.mydomain.com. I edited the tnsnames.ora file to just the base name without the domain portion so they looked like this:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase)
    )
  ) 

I restarted the TNS Listener service (I often use lsnrctl stop and lsnrctl start from an administrator command window [or Windows Powershell] instead of the Services control panel, but both work.) After that, I was able to connect.

Mavaddat Javid's user avatar

answered Dec 19, 2016 at 14:38

Capricorn1's user avatar

Capricorn1Capricorn1

8199 silver badges17 bronze badges

1

For thoses Who are using spring-boot and jdbc for connection.
You have to be careful while writing jdbcUrl in application.properties

With SID in Database connection —
source.datasource.jdbcUrl = jdbc:oracle:thin:@[HOST][:PORT]:SID

With Service name in db connection
globe.datasource.jdbcUrl = jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE

This worked for me :)

answered Jun 16, 2020 at 8:18

surajmall's user avatar

surajmallsurajmall

1761 silver badge7 bronze badges

Starting the OracleServiceXXX from the services.msc worked for me in Windows.

answered Jun 16, 2015 at 7:48

Ishildur Baggins's user avatar

1

For Dbeaver users: try selecting «SID» instead of «Service name» in connection settings.

answered Aug 30, 2021 at 6:49

JanBrus's user avatar

JanBrusJanBrus

1,1979 silver badges13 bronze badges

1

I had the same problem. For me, just writing

sqlplus myusername/mypassword@localhost

did the trick, doing so makes it connect to the default service name, I guess.

Hosana Gomes's user avatar

answered Sep 9, 2014 at 4:01

Hossein's user avatar

HosseinHossein

24.3k35 gold badges121 silver badges225 bronze badges

2

This error can occur when an application makes a new connection for every database interaction or the connections are not closed properly. One of the free tools to monitor and confirm this is Oracle Sql developer (although this is not the only tool you can use to monitor DB sessions).

you can download the tool from oracle site Sql Developer

here is a screenshot of how to monitor you sessions. (if you see many sessions piling up for your application user during when you see the ORA-12514 error then it’s a good indication that you may have connection pool problem).

enter image description here

answered Apr 1, 2013 at 0:21

grepit's user avatar

grepitgrepit

21.3k6 gold badges105 silver badges81 bronze badges

Check to see the database is up. Log onto the server, set the ORACLE_SID environment variable to your database SID, and run SQL*Plus as a local connection.

answered May 29, 2012 at 0:50

DCookie's user avatar

DCookieDCookie

42.7k11 gold badges84 silver badges92 bronze badges

1

I resolved this issue in my linux enviroment updating the IP of my machine in /etc/hosts file.

You can verify your network IP (inet end.) with:

$ifconfig

See if your IP matches with /etc/hosts file:

$cat /etc/hosts

Edit your /etc/hosts file, if nedded:

$sudo gedit /etc/hosts

Bye.

answered Sep 3, 2014 at 15:27

Sergio Marcelo C Figueiredo's user avatar

2

what worked for me was really simple, I just needed to initiate the service manually in the «Windows Services» (services.msc in cmd trompt).
my service name is: OracleServiceXXXXX.

answered May 12, 2016 at 13:57

isabelle martz's user avatar

isabelle martzisabelle martz

1711 gold badge3 silver badges12 bronze badges

1

I had also faced the same problem and spent 3 days to dig it out.

This happens because of your wrong TNS service entry.

First check whether you are able to connect to standby database from primary database using sql > sqlplus sys@orastand as sysdba (orastand is a standby database).

If you are not able to connect then it is a problem with the service. Correct the entry of service name in TNS file at primary end.

Check standby database the same way. Make the changes here too if required.

Make sure the log_archive_dest_2 parameter has the correct service name.

Gryu's user avatar

Gryu

2,1122 gold badges17 silver badges29 bronze badges

answered Jun 26, 2014 at 6:41

user3778101's user avatar

For those that may be running Oracle in a VM (like me) I saw this issue because my VM was running out of memory, which seems to have prevented OracleDB from starting up/running correctly. Increasing my VM memory and restarting fixed the issue.

answered Apr 14, 2016 at 18:14

th3uiguy's user avatar

th3uiguyth3uiguy

1,8791 gold badge12 silver badges8 bronze badges

Lots of answers here, but here comes a working example with code that you can copy and paste and test immediately:

For me the error 12514 was solved after specifying the correct SERVICE_NAME.
You find that on the server in the file tnsnames.ora which comes with 3 predefined service names (one of them is «XE»).

  1. I installed the Oracle Express database OracleXE112 which already comes with some preinstalled demo tables.
  2. When you start the installer you are asked for a password. I entered «xxx» as password. (not used in production)
  3. My server runs on the machine 192.168.1.158
  4. On the server you must explicitely allow access for the process TNSLSNR.exe in the Windows Firewall. This process listens on port 1521.
  5. OPTION A: For C# (.NET2 or .NET4) you can download ODAC11, from which you have to add Oracle.DataAccess.dll to your project. Additionally this DLL depends on: OraOps11w.dll, oci.dll, oraociei11.dll (130MB!), msvcr80.dll.
    These DLLs must be in the same directory as the EXE or you must specify the DLL path in: HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.112.4.0\DllPath. On 64 bit machines write additionally to HKLM\SOFTWARE\Wow6432Node\Oracle\...
  6. OPTION B: If you have downloaded ODAC12 you need Oracle.DataAccess.dll, OraOps12w.dll, oci.dll, oraociei12.dll (160MB!), oraons.dll, msvcr100.dll. The Registry path is HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.121.2.0\DllPath
  7. OPTION C: If you don’t want huge DLL’s of more than 100 MB you should download ODP.NET_Managed12.x.x.x.xxxxx.zip in which you find Oracle.ManagedDataAccess.dll which is only 4 MB and is a pure managed DLL which works in 32 bit and 64 bit processes as well and depends on no other DLL and does not require any registry entries.
  8. The following C# code works for me without any configuration on the server side (just the default installation):
using Oracle.DataAccess.Client;
or
using Oracle.ManagedDataAccess.Client;

....

string oradb = "Data Source=(DESCRIPTION="
    + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.158)(PORT=1521)))"
    + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));"
    + "User Id=SYSTEM;Password=xxx;";

using (OracleConnection conn = new OracleConnection(oradb)) 
{
    conn.Open();
    using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Connection  = conn;
        cmd.CommandText = "select TABLESPACE_NAME from DBA_DATA_FILES";

        using (OracleDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                listBox.Items.Add(dr["TABLESPACE_NAME"]);
            }
        }
    }
}

If the SERVICE_NAME=XE is wrong you get error 12514. The SERVICE_NAME is optional. You can also leave it away.

answered Apr 20, 2017 at 21:19

Elmue's user avatar

ElmueElmue

7,6423 gold badges47 silver badges57 bronze badges

1

In my case the database had ran out of disk space. Which caused it to not respond. Once I cleared up that issue everything worked again.

answered Apr 20, 2014 at 2:12

Pete Brumm's user avatar

Pete BrummPete Brumm

1,65619 silver badges13 bronze badges

1

I got the same error because the remote SID specified was wrong:

 > sqlplus $DATASOURCE_USERNAME/$DATASOURCE_PASSWORD@$DB_SERVER_URL/$REMOTE_SID 

I queried the system database:

select * from global_name;

and found my remote SID («XE»).

Then I could connect without any problem.

answered Oct 13, 2017 at 10:55

Laura Liparulo's user avatar

In my case, round brackets around the SERVICE_NAME was missing in the tnsnames.ora file.

<DBNAME> =
  (DESCRIPTION =
    (ADDRESS_LIST =
     (ADDRESS = (PROTOCOL=TCP)(HOST = nupark-cnvr-ora )(PORT=1521))
    )
    (CONNECT_DATA =
    (SERVER = DEDICATED)
    (SERVICE_NAME = <DBNAME> ***CLOSING ROUND BRACKET WAS MISSING HERE***
    )
  )

LISTENER_<DBNAME> =

  (ADDRESS = (PROTOCOL = TCP)(HOST = nupark-cnvr-ora)(PORT = 1521))

answered Mar 10, 2020 at 17:59

Mosab Sasi's user avatar

Mosab SasiMosab Sasi

1,1308 silver badges11 bronze badges

I had just to replace my connection string

from:

jdbc:oracle:thin:@localhost:1521:xe

To:

jdbc:oracle:thin:@localhost:1521:orcl

Steven's user avatar

Steven

2,0213 gold badges23 silver badges33 bronze badges

answered Oct 27, 2022 at 2:49

rahul Bhavar's user avatar

For me this was caused by using a dynamic ipadress using installation. I reinstalled Oracle using a static ipadress and then everything was fine

answered Dec 3, 2016 at 7:45

Steef's user avatar

SteefSteef

5695 silver badges21 bronze badges

Restarting the VM worked for me

answered Mar 20, 2019 at 3:35

wishman's user avatar

wishmanwishman

7744 gold badges14 silver badges31 bronze badges

My issue was resolved by replacing the’SID’ in URL with ‘service name’ and correct host.

answered Aug 23, 2019 at 13:47

Sir. Hedgehog's user avatar

Sir. HedgehogSir. Hedgehog

1,2603 gold badges17 silver badges40 bronze badges

tnslsnr is up but database is down.

For oracle novice it is not obvious that database may be down while connections are accepted.

I had to start up database manually like that

su - oracle
export ORACLE_SID=XE
sqlplus sys as sysdba

And then in sql console

startup

In my case i failed to startup but got another error message and found the source of a problem — i had to change host name and then database auto startup was functional again.

answered Nov 11, 2019 at 9:38

user3132194's user avatar

user3132194user3132194

2,38123 silver badges17 bronze badges

I have implemented below workaround to resolve this issue.

  1. I have set the ORACLE_HOME using command prompt
    (right click cmd.exe and Run as System administrator).

  2. Used below command

    set oracle_home="path to the oracle home"

  3. Go to All programs —> Oracle -ora home1 —> Configuration migration tools —> Net Manager —> Listener

  4. Select Database Services from dropdown.
    Both Global database name and SID are set to the same (ORCL in my case).
    Set Oracle Home Directory.

Oracle Net Manager window example from oracle documentation:
Oracle Net Manager example

  1. Click on File and save network configuration.

Gryu's user avatar

Gryu

2,1122 gold badges17 silver badges29 bronze badges

answered Nov 29, 2017 at 12:34

Raman B's user avatar

Raman BRaman B

3314 silver badges5 bronze badges

The problem was that my connection string url contained database name instead of SID.
Replacing database name with oracle database connection SID solved this problem.

To know your oracle SID’s you can browse tnsnames.ora file.

XE was the actual SID, so this is how my tomcat connection string looks like now:

    <Resource
       name="jdbc/my_db_conn"
       auth="Container"
       type="javax.sql.DataSource"
       driverClassName="oracle.jdbc.driver.OracleDriver"
       url="jdbc:oracle:thin:@//127.0.0.1:1521/XE"
       username="test_user"
       password="test" />

My server version was «Oracle 11.2 Express», but solution should work on other versions too.

answered Dec 5, 2019 at 12:07

Benas's user avatar

BenasBenas

2,1262 gold badges39 silver badges67 bronze badges

I had a case that I used DBMS where I had to fulfill a db connection form.

I put SID into the Database field and in the dropdown, next to the field, I had had ‘Service Name’ value instead of ‘SID’ value.
(normally I don’t use Oracle database so I’ve not been aware of the difference)

That was the reason I got the error message.

answered Jul 28, 2020 at 16:02

Bronek's user avatar

BronekBronek

10.7k2 gold badges45 silver badges46 bronze badges

The problem can be in the incorrect URL.

For example, I’m using Oracle database (inside VM) with Spring framework and having this issue.

I had in my application.properties file:

spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/orcl12c

But the db version was defferent:

spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/orclcdb

The correct URL can be found in the tnsnames.ora file (this file would be available where the Oracle server, so if you using VM, you should look for this file inside your host VM).
For example for Oracle in the VirtualBox the command to see this file is:

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

Dharman's user avatar

Dharman

31.1k25 gold badges86 silver badges137 bronze badges

answered Apr 17, 2021 at 21:59

x3hree's user avatar

x3hreex3hree

811 gold badge2 silver badges4 bronze badges

In my case for Linux environment, the oracle file at ORACLE_HOME/bin was highlighted in «Red» color with different permissions as below:
enter image description here

I changed the permissions of this file as below:

1) Stop Oracle -> sudo systemctl stop oracle.service
2) Change the permission of oracle file at ORACLE_HOME/bin directory as «sudo chmod 777 oracle«
3) Start Oracle -> sudo systemctl start oracle.service

Then after this change, I checked the status of listener using lsnrctl status.Here, I can see the db instances loaded successfully.

However, I can connect using sqldeveloper only, with sqlplus command line I’m getting ORA-12547: TNS Lost Contact error. So, this can a quick workaround to use sqldeveloper.

Note: Take a backup of oracle file before changing the permissions.

answered Aug 11, 2021 at 13:49

Rohit Gaikwad's user avatar

Rohit GaikwadRohit Gaikwad

3,6773 gold badges18 silver badges40 bronze badges

This is a tricky Oracle error, as it can have lots of possible causes.
It seems to mean that something in this chain of events is failing:

  • Look up the service name in tnsnames.ora
  • Connect to the host in the tnsnames entry
  • Reach the listener on that host
  • Tell the listener that you want to connect to the service specified in the tnsnames entry

Anything that throws that off can cause this error, from a missing bracket in tnsnames.ora, to a connecting to the wrong database host.

If tnsping works, that rules some things out, as it means that we can look up the entry in tnsnames, connect to the host, and contact the listener … so we know, for instance, that the host at least exists, and there is an Oracle listener running there; but the listener is saying the service name is not known. That still leaves a lot of possibilities like:

  • service name in tnsnames.ora is just wrong
  • database instance is not running and/or not registered with the listener
  • we’re connecting to the wrong Oracle host
  • we’re connecting to the wrong listener (wrong port) on the correct Oracle host
  • firewall/networking issue (apparently it’s possible that a firewall could allow tnsping packets through but block other client applications from connecting)

I’ve seen an ORA-12514 with tiny typos in tnsnames.ora … like incorrect indenting. But I suspect tnsping wouldn’t succeed if that is the issue.

When I encountered this most recently, it was due to the 3rd bullet-point above; we were connecting to an Oracle database host — just not the right host; we had to ensure that the hostname in the tnsnames entry was for the Oracle database server that was hosting this particular database service.

Connecting to the Oracle host and running lsnrctl status can help check that the service is known to this listener. Remember that lsnrctl by default checks the default listener name. You may need to check listener.ora to see if there are other names listeners in this database instance.

answered Apr 7 at 18:27

em_bo's user avatar

em_boem_bo

6247 silver badges13 bronze badges

Уже в течении месяца я использовал Oracle APEX VM. После очередной активации виртуальной машины, я попытался осуществить подключение к системному пользователю system. Результатом подключения стала данная ошибка, из-за которой я не могу подключиться к своей БД.

Как исправить эту ошибку?

0xdb's user avatar

0xdb

51.5k198 золотых знаков59 серебряных знаков237 бронзовых знаков

задан 13 мая 2021 в 11:07

AspiringToBeAJune's user avatar

7

Эту ошибка означaет, что прослушивателю не известно имя сервиса, к которому идёт подключение.

Или оно дествительно неверно:

$ sqlplus -l me/me@dbserver:1521/pdb1xxx

ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect
descriptor

Или имя сервиса не зарегестрированно на прослушивателе. Проверить можно так:

$ lsnrctl status|grep pdb1
Service "pdb1" has 2 instance(s).

Если ничего не выводит, то существует множество причин этого. Но если вчера работало, а сегодня нет, и никто ничего не менял, то причина скорее всего одна: БД не стартовала.

ответ дан 13 мая 2021 в 19:36

0xdb's user avatar

0xdb0xdb

51.5k198 золотых знаков59 серебряных знаков237 бронзовых знаков

1

У нас есть приложение, работающее локально, где мы испытываем следующую ошибку:

ORA-12514: TNS: слушатель в настоящее время не знает о запрошенной услуге в дескрипторе соединения

Я тестировал соединение, используя TNSPing, который правильно и
Я попробовал SQLPlus, чтобы попробовать подключиться, что не удалось с той же ошибкой, что и выше. Я использовал этот синтаксис для SQLPlus:

sqlplus username/[email protected][or host name]

Мы проверили, что:

  • Слушатель TNS на сервере запущен.
  • Сам Oracle на сервере запущен.

Мы не знаем никаких изменений, которые были внесены в эту среду.
Что-нибудь еще, что мы можем проверить?

4b9b3361

Ответ 1

У меня была эта проблема, и исправление заключалось в том, чтобы убедиться, что в tnsnames.ora SERVICE_NAME является допустимым именем службы в вашей базе данных. Чтобы узнать правильные имена служб, вы можете использовать следующий запрос в oracle:

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

Как только я обновил tnsnames.ora до:

TEST =
   (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = *<validhost>*)(PORT = *<validport>*))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = *<servicenamefromDB>*)
    )
)

то я побежал:

sqlplus [email protected]

Успех!
Слушатель в основном говорит вам, что любое имя службы, которое вы используете, не является действительной службой в соответствии с БД.

(* Я запускал sqlplus из клиентской рабочей станции Win7 для удаленного БД и обвинял администраторов баз данных;) *)

Ответ 2

Я знаю, что это старый вопрос, но все еще без ответа. Это заняло у меня целый день исследований, но я нашел самое простое решение, по крайней мере, в моем случае (Oracle 11.2 в Windows 2008 R2) и хотел поделиться им.

Ошибка, если смотреть непосредственно, указывает, что слушатель не распознает имя службы. Но где он хранит названия сервисов? В %ORACLE_HOME%\NETWORK\ADMIN\listener.ora

«SID_LIST» — это просто список SID и имен сервисов в паре в формате, который вы можете скопировать или найти.

Я добавил проблему Service Name, затем в панели управления Windows «Службы» произвел «Перезапуск» в службе прослушивателя Oracle. Теперь все хорошо.


Например, ваш файл listener.ora может изначально выглядеть так:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

… И чтобы он распознал имя службы orcl, вы можете изменить его на:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
    (SID_DESC = 
        (GLOBAL_DBNAME = orcl)
        (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
        (SID_NAME = orcl)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

Ответ 3

У меня была эта проблема на сервере Windows 2008 R2 и Oracle 11g

перейдите в Net Manager > Listener > выберите службы базы данных из combox > «Глобальное имя базы данных» должно быть таким же, как «SID» и «Oracle Home Directory» должны быть правильными.

Если у вас нет какой-либо записи для служб баз данных, создайте ее и установите правильную глобальную базу данных, sid и oracle home.

Ответ 4

В моих обстоятельствах ошибка была связана с тем, что у слушателя не была зарегистрирована служба db. Я решил это путем регистрации услуг. Пример:

Мой дескриптор в tnsnames.ora:

LOCALDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = LOCALDB)
    )
  )

Итак, я продолжаю регистрировать сервис в listener.ora вручную:

SID_LIST_LISTENER =
    (SID_DESC =
      (GLOBAL_DBNAME = LOCALDB)
      (ORACLE_HOME = C:\Oracle\product\11.2.0\dbhome_1)
      (SID_NAME = LOCALDB)
    )

Наконец, перезапустите слушателя командой:

> lsnrctl stop
> lsnrctl start

Готово!

Ответ 5

Запуск OracleServiceXXX из services.msc работал у меня в Windows.

Ответ 6

На самом деле это должен быть комментарий к Brad Rippe, но, увы, не хватает репутации. Этот ответ дал мне 90% пути. В моем случае установка и настройка баз данных помещали записи в файл tnsnames.ora для баз данных, которые я запускал. Во-первых, я смог подключиться к базе данных, установив переменные среды (Windows):

set ORACLE_SID=mydatabase
set ORACLE_HOME=C:\Oracle\product\11.2.0\dbhome_1

а затем соединение с помощью

sqlplus / as sysdba

Затем, запустив команду из Brad Rippe, ответьте:

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

показал, что имена не совпадают точно. Записи, созданные с помощью Oracle Database Configuration Assistant, где первоначально:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase.mydomain.com)
    )
  ) 

Имя службы из запроса было просто mydatabase, а не mydatabase.mydomain.com. Я отредактировал файл tnsnames.ora только базовому имени без части домена, чтобы они выглядели следующим образом:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase)
    )
  ) 

Я перезапустил службу прослушивателя TNS (я часто использую lsnrctl stop и lsnrctl start из командной строки администратора [или Windows Powershell] вместо панели управления Services, но обе работают.) После этого я смог подключиться.

Ответ 7

Проверьте, что база данных обновлена. Войдите на сервер, установите переменную среды ORACLE_SID в SID базы данных и запустите SQL * Plus в качестве локального соединения.

Ответ 8

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

вы можете загрузить инструмент с сайта oracle Sql Developer

вот скриншот о том, как контролировать сеансы. (если вы видите много сеансов, накапливающихся для вашего пользователя приложения во время просмотра ошибки ORA-12514, то это хороший признак того, что у вас может быть проблема пула соединений).

enter image description here

Ответ 9

Я также столкнулся с такой же проблемой и потратил 3 дня, чтобы выкопать ее. Это происходит из-за неправильной записи службы TNS. Сначала проверьте, можете ли вы подключиться к резервной базе данных из первичной базы данных, используя sql > sqlplus sys @orastand as sysdba (orastand — резервная база данных), если вы не можете подключиться, это проблема с сервисом. Исправьте запись имени службы в файле TNS на начальном конце. Проверьте этот режим в резервной базе данных, если требуется внести изменения и здесь. и убедитесь, что parmater log_archive_dest_2 имеет правильное имя службы.

Ответ 10

Я решил эту проблему в среде linux, обновляя IP-адрес моей машины в файле /etc/hosts.

Вы можете проверить свой IP-адрес сети (inet end.) с помощью

$ifconfig

Посмотрите, совпадает ли ваш IP файл с файлом /etc/hosts:

$cat /etc/hosts

Отредактируйте файл /etc/hosts, если nedded:

$sudo gedit /etc/hosts

Bye.

Ответ 11

У меня была та же проблема, для меня просто пишу

sqlplus myusername/[email protected]

сделал трюк, поэтому он подключается к имени службы по умолчанию, которое я предполагаю.

Ответ 12

Для тех, кто может работать с Oracle в виртуальной машине (например, я), я видел эту проблему, потому что у моей VM не хватало памяти, что, похоже, помешало OracleDB правильно запущен/запущен. Увеличение памяти VM и перезапуск исправили проблему.

Ответ 13

то, что сработало для меня, было очень просто, мне просто нужно было запустить сервис вручную в «Служб Windows» (services.msc в cmd trompt).
мое имя службы: OracleServiceXXXXX.

Ответ 14

Здесь много ответов, но здесь приведен рабочий пример с кодом, который вы можете скопировать и вставить и протестировать сразу:

Для меня ошибка 12514 была решена после указания правильного SERVICE_NAME.
Вы обнаружите, что на сервере в файле tnsnames.ora, который поставляется с тремя предопределенными именами служб (один из них — «XE» ).

  • Я установил базу данных Oracle Express OracleXE112, которая уже поставляется с предустановленными демонстрационными таблицами.
  • Когда вы запустите программу установки, вас попросят ввести пароль. Я ввел «xxx» в качестве пароля. (не используется в производстве)
  • Мой сервер работает на компьютере 192.168.1.158
  • На сервере вы должны явно разрешить доступ к процессу TNSLSNR.exe в брандмауэре Windows. Этот процесс прослушивает порт 1521.
  • ВАРИАНТ A:. Для С# (.NET2 или .NET4) вы можете загрузить ODAC11, из которого вы должны добавить Oracle.DataAccess.dll в свой проект. Кроме того, эта DLL зависит от: OraOps11w.dll, oci.dll, oraociei11.dll(130MB!), Msvcr80.dll.
    Эти DLL должны находиться в том же каталоге, что и EXE, или вы должны указать путь к DLL в: HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.112.4.0\DllPath. На 64-битных машинах дополнительно записывать HKLM\SOFTWARE\Wow6432Node\Oracle\...
  • ВАРИАНТ B: Если вы загрузили ODAC12, вам нужны Oracle.DataAccess.dll, OraOps12w.dll, oci.dll, oraociei12.dll(160MB!), oraons.dll, msvcr100.dll. Путь реестра HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.121.2.0\DllPath
  • OPTION C: Если вам не нужна огромная DLL более 100 МБ, вы должны скачать ODP.NET_Managed12.xxxxxxxx.zip, в которой вы найдете Oracle.ManagedDataAccess.dll, который составляет всего 4 МБ и представляет собой чистую управляемую DLL, которая также работает в 32-битных и 64-битных процессах и не зависит от какой-либо другой DLL и не требует каких-либо записей в реестре.
  • Следующий код С# работает для меня без какой-либо конфигурации на стороне сервера (только установка по умолчанию):
using Oracle.DataAccess.Client;
or
using Oracle.ManagedDataAccess.Client;

....

string oradb = "Data Source=(DESCRIPTION="
    + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.158)(PORT=1521)))"
    + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));"
    + "User Id=SYSTEM;Password=xxx;";

using (OracleConnection conn = new OracleConnection(oradb)) 
{
    conn.Open();
    using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Connection  = conn;
        cmd.CommandText = "select TABLESPACE_NAME from DBA_DATA_FILES";

        using (OracleDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                listBox.Items.Add(dr["TABLESPACE_NAME"]);
            }
        }
    }
}

Если ошибка SERVICE_NAME=XE неверна, вы получаете ошибку 12514. SERVICE_NAME не является обязательным. Вы также можете оставить его.

Ответ 15

В моем случае в базе данных закончилось дисковое пространство. Это заставило его не отвечать. Как только я выяснил эту проблему, все снова работало.

Ответ 16

Я получил ту же ошибку, потому что указанный удаленный идентификатор безопасности был неправильным:

 > sqlplus $DATASOURCE_USERNAME/[email protected]$DB_SERVER_URL/$REMOTE_SID 

Я запросил системную базу данных:

выберите * из global_name;

и нашел мой удаленный SID ( «XE» ).

Тогда я мог бы подключиться без каких-либо проблем.

Ответ 17

Если вы получили это сообщение об ошибке, но не успешно выполнили TNSPing, как это делали OP, попробуйте эти инструкции для как запустить Oracle и слушателей.

Ответ 18

Для меня это было вызвано использованием динамического ipadress с использованием установки. Я переустановил Oracle, используя статический ipadress, и тогда все было в порядке

Ответ 19

Перезапуск ВМ работал на меня

Ответ 20

Моя проблема была решена путем замены «SID» в URL на «имя службы» и правильный хост.

Ответ 21

Я сделал ниже, чтобы решить эту проблему.

  • Я установил oracle_home в подсказке cmd
    (щелкните правой кнопкой мыши cmd.exe Запуск от имени системного администратора).
    используется ниже команды

    установить oracle_home = «путь к дому оракула»

У меня был установлен оракул в моем диске D:.

  1. И перейти ко всем программам → Oracle -ora home1 → Инструменты настройки конфигурации
    Net Manager → Listener → выберите Database Services из выпадающего меню → Имя глобальной базы данных и SID оба установлены одинаково, в моем случае это ORCL, установите каталог oracle_home. Нажмите «Файл» и сохраните конфигурацию сети.

Ошибка TNS-12514 может возникнуть во множестве случаев, как на windows, так и на unix/linux платформах. Но чаще всего неприятности с подключением происходят именно на windows платформе.

Первое, что необходимо проверить, настройки самого прослушивателя listener.ora:

LISTENER =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
  )

ADR_BASE_LISTENER = C:\app\oracle\product\12.1.0\dbhome_1

Далее следует убедиться, что экземпляр БД запущен.

> export ORACLE_SID=my_sid
> sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL>

Если вместо версии БД мы получаем сообщение:

Connected to an idle instance.

SQL>

то запускаем БД:

SQL>startup

Если подключиться к БД по-прежнему не удается, то проверяем процесс прослушивателя.

LSNRCTL for 64-bit Windows: Version 12.1.0.2.0 - Production on 14-DEC-2015 16:50:50

Copyright (c) 1991, 2014, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 12.1.0.2.0 - Production
Start Date                14-DEC-2015 16:37:40
Uptime                    0 days 0 hr. 13 min. 10 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   C:\app\oracle\product\12.1.0\dbhome_1\listener.ora
Listener Log File         C:\app\oracle\product\12.1.0\dbhome_1\log\diag\tnslsnr\phoenix\listener\alert\log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
The listener supports no services
The command completed successfully

Обычно каждая БД регистрируется автоматически. Если появляется сообщение “прослушиватель не поддерживает сервисов”, то, как правило, экземпляр БД не может зарегистрироваться. При регистрации используются сетевые параметры, заданные по-умолчанию. Если они не совпадают с настройками прослушивателя, то в БД необходимо установить параметр LOCAL_LISTENER. По-умолчанию параметр имеет пустое значение.

SQL> show parameter local_listener;

NAME                                 TYPE        VALUE
------------------------------------ ----------- -------------------------------
local_listener                       string

SQL> alter system set LOCAL_LISTENER='(ADDRESS = (PROTOCOL=TCP)(HOST=localhost)(PORT=1521))' scope=both;

System altered.

SQL> show parameter local_listener;

NAME                                 TYPE        VALUE
------------------------------------ ----------- -------------------------------
local_listener                       string      (ADDRESS = (PROTOCOL=TCP)(HOST=
                                                 =localhost)(PORT=1521))
SQL>

После установки параметра БД автоматически регистрируется для прослушивателя.

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