Ora-12505, tns: слушатель в настоящее время не знает sid, указанный в дескрипторе соединения

5 ответов

Лучший ответ

Ваша база данных Oracle не работает. Может возникнуть проблема с запуском.

Перейдите в командную строку и введите:

SQL> sqlplus / as sysdba

Если вы получили сообщение «подключен к бездействующему экземпляру», введите

SQL> запуск

И дайте мне знать, что вы получите. Если вы не получаете сообщение «подключен к незанятому экземпляру» при запуске SqlPlus, введите:

SQL> установить строки 80 страниц 50

SQL> выберите * из базы данных v $;

И опубликуйте результат здесь.

2

Sam
20 Мар 2013 в 05:07

В 64-разрядной версии Windows 7, Orcale XE 11 моя служба OracleXXETNSListener не работала и немедленно завершала работу, когда я пытался ее запустить.

  1. Добавление

К моему

  1. изменение имени хоста на localhost

  2. перезапуск службы OracleServiceXE в разделе «Система — службы» решил проблему.

Итак, полный раздел listener.ora выглядит так:

Обновлять: Сейчас прошло 5 лет, и у меня была такая же проблема с OracleXE 18c на Win10. Прослушиватель TNS не запускался сразу после успешной установки, потому что oracleXE \ dbhomeXE \ NETWORK \ ADMIN \ listener.ora указывал на localhost.docker.internal вместо localhost.

12

rob2universe
20 Мар 2020 в 06:29

У меня была точно такая же проблема, и, потратив почти 4 часа, пытаясь найти и ответить, наконец, добавив

К моему listener.ora и перезапуск обеих служб XE решил проблему. Я использую 11.2.0 (XE) на Windows 7 x64 без каких-либо заминок до вчерашнего дня. Перезагрузка моего компьютера сегодня утром привела к тому, что слушатель не нашел SID.

Теперь я создаю резервную копию listener.ora и tnsnames.ora.

Кстати, забыл упомянуть, что я изменил имя хоста в обоих файлах с bob.mycompany.com на localhost.

13

Bob 1174
1 Ноя 2013 в 21:07

У меня была такая же проблема, ошибка заключалась в том, что я изменил имя своей машины. Это было решено редактированием listener.ora и переименованием HOST:

1

jotasi
27 Окт 2016 в 11:49

У меня была аналогичная проблема, и я исправил ее, удалив строки «IPC» из listener.ora и tnsnames.ora.

я удалил:

я удалил:

Возможно, это было перебором, но, наконец, через несколько часов это исправлено!

3

BrunoJCM
28 Апр 2015 в 14:41

Processing SQL Exceptions

To handle error conditions, Oracle JDBC drivers throw SQL exceptions, producing instances of the class or its subclass. Errors can originate either in the JDBC driver or in the database itself. Resulting messages describe the error and identify the method that threw the error. Additional run-time information can also be appended.

JDBC 3.0 defines only a single exception, . However, there are large categories of errors and it is useful to distinguish them. Therefore, in JDBC 4.0, a set of subclasses of the exception is introduced to identify the different categories of errors. To know more about this feature, see .

Basic exception handling can include retrieving the error message, retrieving the error code, retrieving the SQL state, and printing the stack trace. The class includes functionality to retrieve all of this information, when available.

See Also:

Retrieving Error Information

You can retrieve basic error information with the following methods of the class:

The following example prints output from a method call:

catch(SQLException e)
{
   System.out.println("exception: " + e.getMessage());
}

This would print the output, such as the following, for an error originating in the JDBC driver:

exception: Invalid column type

Note:

Error message text is available in alternative languages and character sets supported by Oracle.

Printing the Stack Trace

The class provides the method for printing a stack trace. This method prints the stack trace of the throwable object to the standard error stream. You can also specify a object or object for output.

The following code fragment illustrates how you can catch SQL exceptions and print the stack trace.

try { <some code> } 
catch(SQLException e) { e.printStackTrace (); } 
 

To illustrate how the JDBC drivers handle errors, assume the following code uses an incorrect column index:

// Iterate through the result and print the employee names 
// of the code 
 
try { 
  while (rset.next ()) 
      System.out.println (rset.getString (5));  // incorrect column index
}
catch(SQLException e) { e.printStackTrace (); } 
 

Assuming the column index is incorrect, running the program would produce the following error text:

java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OracleResultSetImpl.getDate(OracleResultSetImpl.java:1556)
at Employee.main(Employee.java:41)

Secure External Password Store

As an alternative for large-scale deployments where applications use password credentials to connect to databases, it is possible to store such credentials in a client-side Oracle wallet. An Oracle wallet is a secure software container that is used to store authentication and signing credentials.

Storing database password credentials in a client-side Oracle wallet eliminates the need to embed user names and passwords in application code, batch jobs, or scripts. This reduces the risk of exposing passwords in the scripts and application code, and simplifies maintenance because you do not need to change your code each time user names and passwords change. In addition, if you do not have to change the application code, then it also becomes easier to enforce password management policies for these user accounts.

You can set the connection property to specify the wallet location. The JDBC driver can then retrieve the user name and password pair from this wallet.

See Also:

  • for more information about configuring your client to use secure external password store and for information about managing credentials in it

  • for more information about managing the secure external password store for password credentials

oracle.jdbc Class OracleDriver

All Implemented Interfaces:
java.sql.Driver
public class OracleDriver
extends oracle.jdbc.driver.OracleDriver

The Oracle JDBC driver class that implements the interface.

Register the JDBC drivers

To access a database from a Java application, you must first provide the code to register your installed driver with your program. You do this with the static method of the class. This class provides a basic service for managing a set of JDBC drivers. The method takes as input a «driver» class, that is, a class that implements the interface, as is the case with .

Note: Alternatively, you can use the method of the class to load the JDBC drivers directly. For example: . However, this method is valid only for JDK-compliant Java virtual machines. It is not valid for Microsoft Java virtual machines.

You register the driver only once in your Java application.

Open a Connection to a database

Once you have registered the driver, you can open a connection to the database with the static method of the class. The type of the object returned is .

Исключение при подключении к базе данных: TNS: слушатель в настоящее время не знает SID, указанного в дескрипторе подключения.

http-equiv=»Content-Type» content=»text/html;charset=UTF-8″>style=»clear:both;»>

Это исключение произошло, когда eclipse подключился к базе данных:

java.sql.SQLException: Listener refused the connection with the following error:ORA-12505, TNS:listener does not currently know of SID given in connect descriptorThe Connection descriptor used by the client was:localhost:1521:orcl

А для Oracle sql разработчик не может нормально подключиться к базе данных, как показано на рисунке:

Решение:

Найдите файл конфигурации listener.ora в базе данных:

# listener.ora Network Configuration File: E:\app\hp\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora# Generated by Oracle configuration tools.SID_LIST_LISTENER =  (SID_LIST =    (SID_DESC =      (SID_NAME = CLRExtProc)      (ORACLE_HOME = E:\app\hp\product\11.2.0\dbhome_1)      (PROGRAM = extproc)      (ENVS = «EXTPROC_DLLS=ONLY:E:\app\hp\product\11.2.0\dbhome_1\bin\oraclr11.dll»)(Если есть это предложение, его нужно удалить)    )  )LISTENER =  (DESCRIPTION_LIST =    (DESCRIPTION =      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))    )    (DESCRIPTION =      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))    )  )ADR_BASE_LISTENER = E:\app\hpПосле модификации: (красный шрифт — добавленный код)

# listener.ora Network Configuration File: E:\app\hp\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora# Generated by Oracle configuration tools.SID_LIST_LISTENER =  (SID_LIST =    (SID_DESC =      (SID_NAME = CLRExtProc)      (ORACLE_HOME = E:\app\hp\product\11.2.0\dbhome_1)      (PROGRAM = extproc)    )    (SID_DESC =    (GLOBAL_DBNAME = ORCL)    (ORACLE_HOME = E:\app\hp\product\11.2.0\dbhome_1)    (SID_NAME = ORCL)    )  )LISTENER =  (DESCRIPTION_LIST =    (DESCRIPTION =      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))    )    (DESCRIPTION =      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))    )  )

После модификации перезапустите сервис, ничего страшного!ADR_BASE_LISTENER = E:\app\hp

Перепечатано по адресу: https://www.cnblogs.com/little-ming/archive/2013/02/11/2910067.html

Интеллектуальная рекомендация

1. Для реальных сигналов (для понимания): A (ω) является соотношением амплитуды выходного сигнала и амплитуды входного сигнала, называемого частотой амплитуды. Φ (ω) — это разница межд…

Один. вести Многие люди задавали некоторые вопросы о создании проекта Flex + LCDS (FDS) в сообщениях и группах. Из-за операции ее трудно четко объяснить, поэтому я написал простой учебник (я обещал эт…

package com.example.phonehttp; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.widget.ScrollView; import android.widget.TextView; public class MainActi…

Он предназначен для реализации подкласса того же родительского класса с родительским классом. Полиморфизм Один и тот же ссылочный тип использует разные экземпляры для выполнения разных операций; Идея …

тема: Объедините два упорядоченных слоя в новый заказанный список и возврат. Новый список состоит из всех узлов двух связанных списков, данных сплавным. Пример: Анализ: два связанных списка состоит в …

Вам также может понравиться

D. Самая ценная строка Пример ввода 2 2 aa aaa 2 b c Образец вывода aaa c На самом деле, будучи задетым этим вопросом, вы должны быть осторожны. После инвертирования строки, если две строки имеют один…

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surro…

calc () может быть очень незнакомым для всех, и трудно поверить, что calc () является частью CSS. Поскольку он выглядит как функция, почему он появляется в CSS, поскольку это функция? Этот момент такж…

Основываясь на дереве регрессии, сформированном CART, а также на предварительной и последующей обрезке дерева, код выглядит следующим образом:…

Откат Обновление в режиме онлайн с версии Centos (CentOS Linux версии 7.3.1611 (Core) до CentOS Linux версии 7.5.1804 (Core)) # ошибка соединения yum-ssh после обновления yexpected key exchange group …

Support for Oracle Advanced Security

Oracle Advanced Security provides the following security features:

  • Data Encryption

    Sensitive information communicated over enterprise networks and the Internet can be protected by using encryption algorithms, which transform information into a form that can be deciphered only with a decryption key. Some of the supported encryption algorithms are RC4, DES, 3DES, and AES.

    To ensure data integrity during transmission, Oracle Advanced Security generates a cryptographically secure message digest. Starting from Oracle Database 12c Release 1 (12.1), the SHA-2 list of hashing algorithms are also supported and Oracle Advanced Security uses the following hashing algorithms to generate the secure message digest and includes it with each message sent across a network:

    • MD5

    • SHA1

    • SHA256

    • SHA384

    • SHA512

    This protects the communicated data from attacks, such as data modification, deleted packets, and replay attacks.

    The following code snippet shows how to calculate the checksum using any of the algorithms mentioned previously:

    prop.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_NET_CHECKSUM_TYPES, "( MD5, SHA1, SHA256, SHA384 or SHA512 )");
    prop.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_NET_CHECKSUM_LEVEL, "REQUIRED");
    
  • Strong Authentication

    To ensure network security in distributed environments, it is necessary to authenticate the user and check his credentials. Password authentication is the most common means of authentication. Oracle Database enables strong authentication with Oracle authentication adapters, which support various third-party authentication services, including SSL with digital certificates. Oracle Database supports the following industry-standard authentication methods:

    • Kerberos

    • Remote Authentication Dial-In User Service (RADIUS)

    • Secure Sockets Layer (SSL)

See Also:

JDBC OCI Driver Support for Oracle Advanced Security

If you are using the JDBC OCI driver, which presumes that you are running from a computer with an Oracle client installation, then support for Oracle Advanced Security and incorporated third-party features is fairly similar to the support provided by in any Oracle client situation. Your use of Advanced Security features is determined by related settings in the file on the client computer.

Note:

Starting from Oracle Database 12c Release 1 (12.1), Oracle recommends you to use the configuration parameters present in the new XML configuration file instead of the OCI-specific configuration parameters present in the file. However, the configuration parameters present in the file are still supported. For more information about the file, see .

Starting from Oracle Database 11g Release 1, the JDBC OCI driver attempts to use external authentication if you try connecting to a database without providing a password. The following are some examples using the JDBC OCI driver to connect to a database without providing a password:

SSL Authentication

Using SSL authentication to connect to the database.

Example 9-1 Using SSL Authentication to Connect to the Database

import java.sql.*;
import java.util.Properties;
 
public class test
{
    public static void main( String [] args ) throws Exception
    {
        String url = "jdbc:oracle:oci:@"
         +"(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=localhost)(PORT=5221))"
         +"(CONNECT_DATA=(SERVICE_NAME=orcl)))";
        Driver driver = new oracle.jdbc.OracleDriver();
        Properties props = new Properties();
        Connection conn = driver.connect( url, props );
        conn.close();
    }
}

Using Data Source

uses a data source to connect to the database.

Example 9-2 Using a Data Source to Connect to the Database

import java.sql.*; 
import javax.sql.*; 
import java.util.Properties; 
import oracle.jdbc.pool.*; 
 
public class testpool { 
    public static void main( String args ) throws Exception 
    { String url = "jdbc:oracle:oci:@" +"(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=localhost)(PORT=5221))"
 +"(CONNECT_DATA=(SERVICE_NAME=orcl)))"; 
    OracleConnectionPoolDataSource ocpds = new OracleConnectionPoolDataSource(); 
    ocpds.setURL(url); 
    PooledConnection pc = ocpds.getPooledConnection(); 
    Connection conn = pc.getConnection(); 
    } 
    }

JDBC Thin Driver Support for Oracle Advanced Security

Решение

Откройте файл Oracle listener.ora

Путь: D: \ SoftwareDevelopment \ Oracle \ product \ 11.2.0 \ dbhome_1 \ NETWORK \ ADMIN \ listener.ora (подробности см. В собственном пути установки)

Содержимое измененного файла выглядит следующим образом

Что вы добавили красным

Красная часть выше означает:Использовать указанный SID_NAME для сопоставления глобальной базы данных, Где ORACLE_HOME указывает путь установки экземпляра Oracle

GLOBAL_DBNAME — этоИмя глобальной базы данных (указывается в процессе установки)

Вас впечатлило изображение выше?

Затем перезапустите службу прослушивателя Oracle OracleOraDb11g_home1TNSListener

перерегистрировать

Успешно подключено!

Processing SQL Exceptions

To handle error conditions, Oracle JDBC drivers throw SQL exceptions, producing instances of the class or its subclass. Errors can originate either in the JDBC driver or in the database itself. Resulting messages describe the error and identify the method that threw the error. Additional run-time information can also be appended.

JDBC 3.0 defines only a single exception, . However, there are large categories of errors and it is useful to distinguish them. Therefore, in JDBC 4.0, a set of subclasses of the exception is introduced to identify the different categories of errors. To know more about this feature, see .

Basic exception handling can include retrieving the error message, retrieving the error code, retrieving the SQL state, and printing the stack trace. The class includes functionality to retrieve all of this information, when available.

See Also:

Retrieving Error Information

You can retrieve basic error information with the following methods of the class:

The following example prints output from a method call:

catch(SQLException e)
{
   System.out.println("exception: " + e.getMessage());
}

This would print the output, such as the following, for an error originating in the JDBC driver:

exception: Invalid column type

Note:

Error message text is available in alternative languages and character sets supported by Oracle.

Printing the Stack Trace

The class provides the method for printing a stack trace. This method prints the stack trace of the object to the standard error stream. You can also specify a object or object for output.

The following code fragment illustrates how you can catch SQL exceptions and print the stack trace.

try { <some code> } 
catch(SQLException e) { e.printStackTrace (); } 
 

To illustrate how the JDBC drivers handle errors, assume the following code uses an incorrect column index:

// Iterate through the result and print the employee names 
// of the code 
 
try { 
  while (rset.next ()) 
      System.out.println (rset.getString (5));  // incorrect column index
}
catch(SQLException e) { e.printStackTrace (); } 
 

Assuming the column index is incorrect, running the program would produce the following error text:

java.sql.SQLException: Invalid column index
at oracle.jdbc.OracleDriver.OracleResultSetImpl.getDate(OracleResultSetImpl.java:1556)
at Employee.main(Employee.java:41)

Support for JDBC 4.1 Standard

Oracle Database 12c Release 1 (12.1) JDBC drivers provide support for JDBC 4.1 standard through JDK 7. This section describes the following methods that are supported in this release:

setClientInfo Method

The method sets the value of the property providing client information. This method accepts keys of the form . The JDBC driver supports any combination.

Note:

The method supports the namespace among other namespaces. But, there are differences between using the namespace and any other namespace. With the namespace, the method supports only the following keys:

Also, the information associated with any other namespace is communicated through the network using a single protocol, while information associated with the OCSID namespace is communicated using a different protocol. The protocol used for the OCSID namespace is also used by the OCI C Library and the 10g thin driver to send end-to-end metrics values.

The method checks the Java permission and if the security check fails, then it throws a . It supports permission name patterns of the form . The method either sets or clears all pairs, so it requires that the permission name must be set to an asterisk (.

The method is backward compatible with the and the methods, and can use DMS to set client tags.

Note:

Starting from Oracle Database 12c Release 1 (12.1), the method is deprecated.

See Also:

for more information about end-to-end metrics and DMS metrics.

Monitoring Database Operations

Many Java applications do not have a database connection, but they need to track database activities on behalf of their functionalities. For such applications, Oracle Database 12c Release 1 (12.1) introduces the tag that can be associated with a thread in the application when the application does not have explicit access to a database. The DBOP tag is associated with a thread through the invocation of DMS APIs, without requiring an active connection to the database. When the thread sends the next database call, then DMS propagates these tags through the connection along with the database call, without requiring an extra round trip. In this way, applications can associate their activity with database operations while factorizing the code in the Application layer.The tag composes of the following:

  • Database operation name

  • The execution ID

  • Operation attributes

The method supports the tag. The method sets the value of the tag to monitor the database operations. When the JDBC application connects to the database and a database round-trip is made, the database activities can be tracked. For example, you can set the value of the tag to in the following way:

...
Connection conn = DriverManager.getConnection(myUrl, myUsername, myPassword);
conn.setClientInfo("E2E_CONTEXT.DBOP", "foo");
Statement stmt = conn.createStatement();
stmt.execute("select 1 from dual");  // DBOP tag is set after this
...

getObject Method

The method retrieves an object, based on the parameters passed. Oracle Database 12c Release 1 (12.1) supports the following two new methods:

Method 1

<T> T getObject(int parameterIndex,
                java.lang.Class<T> type)
            throws SQLException

Method 2

<T> T getObject(java.lang.String parameterName,
                java.lang.Class<T> type)
            throws SQLException

These methods support the conversions listed in the JDBC specification and also the additional conversions listed in . The Oracle Database 12c Release 1 (12.1) drivers also support conversions to some additional classes, which implement one or more static methods, if any of the following criteria is met:

  • No other conversion is specified in JDBC specification or

  • The argument defines one or more public static single argument methods named

  • One or more of the methods take an argument that is a value of a type supported because of JDBC specification or

This release of JDBC drivers convert the value to a type specified in the JDBC specification, or in and then call the corresponding method with the converted value as the argument. If there is more than one appropriate method, then the JDBC driver chooses one method in an unspecified way.

Example

ResultSet rs = . . . ;
Character c = rs.getObject(1, java.lang.Character.class);

The Character class defines the following method:

public static Character valueOf(char c);

specifies that can be converted to . So, if the first column of the is a , then the method converts that value to a and passes the value to the method and returns the resulting object.

Closing JDBC Objects

BEA Systems recommends—and good programming practice dictates—that you always close JDBC objects, such as , , and , in a block to make sure that your program executes efficiently. Here is a general example:

Abandoning JDBC Objects

You should also avoid the following practice, which creates abandoned JDBC objects:

The first line in this example creates a result set that is lost and can be garbage collected immediately.

Troubleshooting Problems with Shared Libraries on UNIX

When you install a native two-tier JDBC driver, configure WebLogic Server to use performance packs, or set up BEA WebLogic Server as a Web server on UNIX, you install shared libraries or shared objects (distributed with the WebLogic Server software) on your system. This document describes problems you may encounter and suggests solutions for them.

The operating system loader looks for the libraries in different locations. How the loader works differs across the different flavors of UNIX. The following sections describe Solaris and HP-UX.

Support for Login Authentication

Basic login authentication through JDBC consists of user names and passwords, as with any other means of logging in to an Oracle server. Specify the user name and password through a Java properties object or directly through the method call. This applies regardless of which client-side Oracle JDBC driver you are using, but is irrelevant if you are using the server-side internal driver, which uses a special direct connection and does not require a user name or password.

Starting with Oracle Database 12c Release 1 (12.1.0.2), the Oracle JDBC Thin driver supports the client ability when you are running your application with a JDK such as JDK 8, which supports the algorithm. If you are running an application with JDK 7, then you must add a third-party security provider that supports the algorithm, otherwise the driver will not support the new password verifier that requires the client ability.

If you are using Oracle Database 12c Release 1 (12.1.0.2) with the parameter set to , then keep the following points in mind:

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Все про сервера
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: