что такое реестр oracle
Что такое реестр oracle
Начиная с версии Oracle 11.1 GUI утилита sqlplusw.exe объявлена как устаревшая (deprecated) и исключена из состава дистрибутива. Теперь приходиться использовать только консольную версию — sqlplus.exe. При её использовании, с русским языком, возникают проблемы. Сообщения самой sqlplus и сообщения выводимые скриптами (это разные вещи) отображаются не корректно (крякозябрами или символами псевдографики). Еще, некоторые стали задавать вопрос, как установить рабочую папку чтобы выполнялись вложенные скрипты. Разберёмся по порядку:
Проблемы некорректных сообщений возникают из-за того что консоль по умолчанию выводит всё в кодировке OEM DOS 866, а скрипты это обычно текстовые файлы в кодировке MS WIN 1251. Кодировка сообщений sqlplus зависит от переменной NLS_LANG, а т.к. базы с данными на русском языке обычно создаются в кодировке CL8MSWIN1251 (не RU8PC866), то и переменные NLS_LANG устанавливаются соответственно как CL8MSWIN1251. Т.е. проблема из-за несовпадения кодировок консоли и программ, которые выводят сообщения на консоль.
1) Чтобы русские сообщения отображались в консоли корректно нужно соблюсти ТРИ условия.
1. В свойствах консоли (правой мышью на заголовке окна cmd) должен быть установлен unicode шрифт, например Lucida Console.
2. За кодировку выводимых сообщений отвечает третья часть переменной NLS_LANG и она должна быть CL8MSWIN1251 (пример, AMERICAN_CIS.CL8MSWIN1251).
3. Нужно переключить кодовую страницу консоли на 1251, командой
Если все три условия соблюдены — проблем с русскими буквами не будет.
Примечания:
1. Переменную NLS_LANG можно задавать тремя способами:
а) (глобально) (по умолчанию) В реестре в HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE. Здесь переменная может быть в нескольких местах, особенно если на компьютере несколько ORACLE_HOME. Менять её нужно для того ORACLE_HOME из которого запускается sqlplus. Для 64-битных систем существует еще одна ветка реестра для Oracle — HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE. Если вы меняете переменную, а результат не меняется, хотя все остальные условия соблюдены, значит вы меняете не ту переменную, попробуйте поменять вообще все NLS_LANG, которые найдете или см.п. в).
б) (локально) Для конкретной DOS сессии. Прямо в консоли командой set
C:> SET NLS_LANG=AMERICAN_CIS.CL8MSWIN1251
в) (супер глобально) Задать как переменную окружения в ОС. Делать так я настоятельно НЕ рекомендую. Но, такая установка перекрывает переменную в реестре, поэтому если вы меняете NLS_LANG в реестре, а результат не меняется — проверьте переменные окружения, командой set без параметров.
2. Изменение переменной NLS_LANG на глобальном уровне влияет на все другие программы работающие с Oracle, например EXPIMP. Поэтому следует быть осмотрительным и для безопастности, для запуска sqlplus использовать bat или cmd файл в котором менять NLS_LANG на уровне текущей сессии.
2) Чтобы сообщения sqlplus выводились корректно см. п. 1).
Если сделать всё как описано в п.1) то все сообщения sqlplus будут выводить корректно на русском языке. Если у вас нет проблем с английским то я рекомендую выводит сообщения sqlplus на английском языке. Потому что в англоязычном сегменте сети гораздо больше информации чем в русском и если возникнет ошибка то по английскому сообщению найти решение будет проще и быстрее.
За язык сообщений sqlplus и других консольных утилит Oracle отвечает первая часть переменной NLS_LANG. Чтобы все сообщения было на английском языке — её нужно установить как AMERICAN (например, AMERICAN_CIS.CL8MSWIN1251).
3) Как установить рабочую папку чтобы выполнялись вложенные скрипты.
Для этого нужно запустить sqlplus из рабочей папки. Для примера предположим что в качестве рабочей папки нужно использовать папку c:\EGRP\SCRIPTS и запустить скрипт c:\EGRP\SCRIPTS\UPDATE.sql, который вызывает из себя другие скрипты, некоторые из которых находиться в подпапках c:\EGRP\SCRIPTS.
C:\> cd c:EGRP\SCRIPTS
c:\EGRP\SCRIPTS>c:\app32\admin\product\11.2.0\client_1\bin\sqlplus.exe /nolog
SQL> @update
(на картинке еще отображен момент переключения кодовой страницы)
Для удобства использования, можно создать bat или cmd файл для запуска sqlplus.
REM echo off
REM Установка рабочей папки (можно убрать)
cd c:\egrp\scripts
SET NLS_LANG=RUSSIAN_CIS.CL8MSWIN1251
chcp 1251
break
REM Два варианта запуска sqlplus
c:\app\admin\product\11.2.0\dbhome_1\BIN\sqlplus.exe /nolog
REM c:\app\admin\product\11.2.0\dbhome_1\BIN\sqlplus.exe /nolog @UPDATE
exit
Примечания:
— echo off — не выводить выполняемые команды на консоль, а только результат их выполнения. Я предпочитаю видеть что происходит поэтому отключил (REM) эту команду.
15 Configuration Parameters and the Registry
This chapter describes use of the registry for various Oracle Database for Windows components. It also lists recommended values and ranges for configuration parameters.
This chapter contains these topics:
About Configuration Parameters
Oracle Database for Windows uses configuration parameters to locate files and specify run-time parameters common to all Oracle products. When an Oracle program or application requires a translation for a particular configuration variable, Oracle Database for Windows uses the associated parameter. All Oracle parameters are stored in the registry.
Registry Overview
Oracle Database for Windows stores its configuration information in a repository (the registry) that is organized in a tree format. The tree format consists of keys in the registry and parameter values for the keys. Keys and parameter values can be viewed and modified in Registry Editor.
Keys are folders that appear in the left pane of a Registry Editor window. A key contains subkeys or parameters.
Although Registry Editor lets you view and modify registry keys and parameter values, you normally are not required to do so. In fact, you can render your system useless if you make incorrect changes. Therefore, only advanced users should edit the registry. Back up your system before making any changes in the registry.
Parameters in Registry Editor appear as a string, consisting of three components:
Value class or type of entry
For example, parameter ORACLE_SID can have the following entry in the registry:
Value classes for Oracle Database for Windows parameters are:
Binary value with a REG_DWORD prefix to identify a value entry as a dword (hexadecimal data) entry
Most Oracle Database for Windows parameter values are string types. Use Oracle Universal Installer defaults when a type is not given.
Registry Parameters
This section describes Oracle Database for Windows registry parameters for the following keys. Other products, such as Oracle Enterprise Manager, have additional keys and parameters that are not described in this chapter.
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_HOME_NAME
Each time you install Oracle products into a new Oracle home on your computer, HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_ HOME_NAME is created. This subkey contains parameter values for most Oracle products.
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_ HOME_NAME includes the following parameters for an Oracle home directory. Depending on products you install, additional parameters can also be created. See your Windows development manuals.
MSHELP_TOOLS
Specifies the location of Windows help files. The default value is
NLS_LANG and Other Globalization Parameters
Specifies supported language, territory, and character set. This parameter specifies the language in which messages appear, the territory and its conventions for calculating week and day numbers, and the character set displayed. Oracle Universal Installer sets this value during installation based on the language setting of the operating system.
The default value for NLS_LANG, if not set, is AMERICAN_AMERICA.US7ASCII.
There are other globalization parameters that can be set along NLS_LANG to override some values implicitly determined by NLS_LANG. These parameters are:
The following parameters can also be set along NLS_LANG to determine globalization behavior that is independent from the value of NLS_LANG:
All globalization parameters set in the environment and Registry for a database client are ignored if NLS_LANG is not set.
See Oracle Database Globalization Support Guide for more information about NLS_LANG and other globalization parameters
ORA_CWD
Specifies current working directory. For example, if you set this parameter and then use ORADIM, a log file called oradim.log is created in this directory. This parameter must be manually set.
ORA_SID_AUTOSTART
Starts Oracle Database when OracleService SID service is started. The default value is true.
ORA_SID_PFILE
ORA_SID_SHUTDOWN
ORA_SID_SHUTDOWN_TIMEOUT
ORA_SID_SHUTDOWNTYPE
ORA_TZFILE
Specifies location of time zone file. Each file contains:
Valid time zone names
Abbreviation for standard time
Abbreviation for daylight savings time
In previous releases, the default value for ORA _TZFILE was
Beginning with Oracle Database 11 g Release 2 (11.2), the default value is
Oracle Database Globalization Support Guide for additional details about time zone files
ORACLE_AFFINITY
Each name setting must be the name of a background thread, user for non-background (shadow) threads, or def for any thread type not handled specifically.
Each affinity setting must be a valid affinity mask (or its numeric equivalent) for the corresponding name. Process affinity masks are used only when Oracle services are first started. Each thread’s affinity is set only when the individual thread is started (for example, at database startup time for the background threads).
ORACLE_BASE
ORACLE_GROUP_NAME
ORACLE_HOME
Specifies Oracle home directory in which Oracle products are installed. This directory is immediately beneath the Oracle base directory in the Oracle directory hierarchy. The default value is the drive letter and name that you specify during installation.
ORACLE_HOME_KEY
The HKEY_LOCAL_MACHINE location of Oracle parameters. The default value is software\oracle\HOME ID.
ORACLE_HOME_NAME
Specifies home name of Oracle home directory in which Oracle products are installed. The default value is the name that you specify during installation.
ORACLE_PRIORITY
Determines Windows scheduling priorities of threads within the Oracle Database management system process. The format is:
ORACLE_PRIORITY is not automatically created for you in the registry. When it is not defined in the registry, Windows default values are used for thread priorities.
ORACLE_SID
Specifies the name of the Oracle Database instance on the host computer. The value of this parameter is the SID for the instance. The default value is specified by the entry in the Database Identification window of Oracle Universal Installer.
OSAUTH_PREFIX_DOMAIN
RDBMS_ARCHIVE
RDBMS_CONTROL
SQLPATH
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE
This subkey contains the following parameters:
INST_LOC
Specifies the location of Oracle Universal Installer files. The default value is System Drive :\program files\oracle\inventory.
Specifies the location of Oracle Objects for OLE message files. The default value is ORACLE_HOME \oo4o\mesg.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet contains four keys:
The first three are used by the operating system. You can edit only the Services subkey, which contains:
Parameters for Oracle Counters for Windows Performance Monitor
Oracle Counters for Windows Performance Monitor parameters appear in:
where ORACLE ver refers to whatever version of Oracle Database is installed.
For Oracle Counters for Windows Performance Monitor to display information for Oracle Database performance objects, it must log in to the database. Modify the following parameters if the default information is not applicable or if you want to access another database:
Hostname displays the SID of the database that Oracle Counters for Windows Performance Monitor will connect to. The default value is blank, causing Oracle Counters for Windows Performance Monitor to connect to the default database on the computer.
Password displays the encrypted password for the user name to access the database.
Oracle Counters for Windows Performance Monitor requires the following parameters as entry points:
The following parameters specify Oracle Counters for Windows Performance Monitor log file and object configuration files:
Parameters for Oracle Database Services
HKEY_LOCAL_MACHINE\SYSTEM\CURRENTCONTROLSET\SERVICES subkey contains additional subkeys that correspond to each Oracle Database service.
Each service subkey contains the following parameters:
ImagePath specifies the fully qualified path name of the executable started by the service and any command-line arguments passed into the executable at run time. The default value is the path to the executable file of the product.
Oracle RAC Registry Parameters
Oracle RAC registry values are based on the clusterware. If you are not using the clusterware, then some of this information may not be applicable to your particular cluster environment.
Oracle RAC is not supported on Windows XP, Windows Vista, Windows 7, and any 32-bit Windows operating system.
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\OCR
This subkey contains the following values:
OCRROOT points to the location of the Oracle Cluster Registry file
LOCAL_ONLY which is set to False for a cluster installation and True for a single-instance database installation
Managing Registry Parameters with regedit
Do not edit your registry unless absolutely necessary. If an error occurs in your registry, then Oracle Database for Windows can stop functioning, and the registry itself can become unusable.
Modifying a Parameter Value with regedit
To edit Oracle-related settings:
Start Registry Editor in one of two ways:
From the command prompt, enter:
The Registry Editor window appears.
Navigate to the values you want to view or modify by double-clicking appropriate keys.
The left-hand side of the window shows the hierarchy of registry keys, and the right-hand side of the window shows various values associated with a key.
Double-click the parameter to edit.
The String Editor dialog appears:
Description of the illustration stringre.gif
Make any necessary edits.
Choose Exit from the Registry menu.
Adding a Registry Parameter with regedit
To add a parameter to the registry:
Start Registry Editor in one of two ways:
From the command prompt, enter:
The Registry Editor window appears.
Navigate to the key to which you want to add the new value.
Choose Add Value from the Edit menu.
The Add Value dialog appears:
Description of the illustration addvalue.gif
In the Value Name field, type the name of the value that you want to add to the currently selected key.
In the Data Type list, select the data type that you want to assign to the added value:
Binary value with a REG_DWORD prefix to identify a value entry as a DWORD (hexadecimal data) entry
The String Editor dialog appears:
Description of the illustration stringre.gif
Type the value for the parameter.
Registry Editor adds the parameter.
Choose Exit from the Registry menu.
Managing Registry Parameters with Oracle Administration Assistant for Windows
Instead of using regedit to add, edit, and delete parameters for an Oracle home, you can use the Oracle Home Configuration snap-in, one of several snap-ins included as part of Oracle Administration Assistant for Windows. You must have Microsoft Management Console on your computer to use this product.
See «HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_HOME_NAME» for more information about Oracle home parameters.
Starting Oracle Administration Assistant for Windows
To start Oracle Administration Assistant for Windows:
Oracle Administration Assistant for Windows starts.
Right-click the Oracle home that you want to modify.
Description of the illustration admin1.gif
Description of the illustration admin2.gif
Adding Oracle Home Parameters
To add an Oracle home parameter:
Click Add in the Properties dialog.
The Add Value dialog appears.
Description of the illustration admin3.gif
Enter the name in the Parameter Name field.
Enter the value in the Parameter Value field.
Editing Oracle Home Parameters
Select the parameter in the Other Settings list in the Properties dialog.
Description of the illustration admin4.gif
The Edit Value dialog appears.
Description of the illustration admin5.gif
Deleting Oracle Home Parameters
To delete an Oracle home parameter:
Select the parameter in the Other Settings list in the Properties dialog.
Modifying Oracle Counters for Windows Performance Monitor Parameters
Using operfcfg
If you run the following command, then operfcfg.exe does not prompt for a password:
In the final example, you change host name to a blank value, causing Oracle Counters for Windows Performance Monitor to connect to the default database on the computer. The current user name and password must be valid user accounts on this database. Enter:
Using Oracle Administration Assistant for Windows
Oracle Counters for Windows Performance Monitor snap-in is part of Oracle Administration Assistant for Windows. You must have Microsoft Management Console on your computer to use this product.
To use Oracle Counters for Windows Performance Monitor snap-in:
Oracle Administration Assistant for Windows starts.
The Performance Monitor Properties dialog appears.
FAQ по Oracle Client
За время работы с Oracle Database и Microsoft SQL Server Integration Services я собрал 2 FAQ-а. Первый — по Oracle Client — я публикую здесь, а второй — по коннекторам SSIS к Oracle, следующим постом.
Что такое Oracle Client?
Это промежуточное ПО, предназначенное для доступа к Oracle Database. Некоторые приложения имеют встроенного клиента. Встраиваемый клиент, предназначенный для разработчиков, называется Instant Client.
Откуда скачать Oracle Client?
Если Вы возьмете клиента от более старшей версии это будет плюсом, поскольку не придется его обновлять на работающей системе, когда потребуется соединяться со следующей СУБД Oracle.
Не перепутайте Oracle Client и Oracle Instant Client, предназначенный для разработчиков. Так же, не качайте Data Access Components, поскольку DAC, помимо Oracle Client, содержит много средств, нужных только для разработки приложений.
Установка клиента Oracle 12c 32-bit не проходит после установки Oracle 12c 64-bit клиента (или наоборот)
Если Вы только что установили одного из клиентов Oracle 12c и не перезагружались, перезагрузитесь.
Программа установки Oracle Client, называемая Oracle Universal Installer, создает службу OracleRemExecService, которая согласно неофициальному описанию нужна только для OUI и должна исчезнуть после перезагрузки. В реальности она не исчезает, но и не запускается при старте ПК. Является ли правильным остановить службу, я не знаю, но это тоже помогает.
Как настроить подключение к СУБД Oracle в приложении, использующем Oracle Client?
Со стороны прикладного программного обеспечения, работающего через Oracle Client, для указания БД может быть использовано имя сервиса TNS или строка конфигурации, содержащая часть объявления имени сервиса TNS.
В первом случае в папке Oracle Client в «\network\admin\tnsnames.ora» укажите:
При этом, в приложениях в поле TNS Service Name указывается имя подключения.
Следует иметь ввиду, что в приложении, запускаемом в 32-х битной среде, используется Oracle Client 32-bit, а в 64-х битной среде используется Oracle Client 64-bit, поэтому может потребоваться сделать «tnsnames.ora» в обоих клиентах.
Что такое SERVICE_NAME и SID?
Подключение к базе данных по сети со стороны сервера обслуживает промежуточное ПО, называемое Listener.
SID это уникальный идентификатор базы данных Oracle на машине, а SERVICE_NAME, это идентификатор базы данных, заданный в Listener. Таким образом, одна и та же база данных, может быть доступна под разными SERVICE_NAME, но только под одним SID. Вас, поскольку Вы находитесь снаружи Listener-а, волнует SERVICE_NAME.
Как адресовать таблицы в Oracle?
По-умолчанию пользователь Oracle обращается к таблицам в своей схеме. Для того, что бы запрос обращался к одним и тем же таблицам из под любого пользователя, нужно указывать имя схемы перед точкой. Например, BM9.BM_CUSTOMER_CONTACT адресует таблицу BM_CUSTOMER_CONTACT в схеме BM9.
Что такое схема и база данных в Oracle?
База данных в СУБД Oracle = отдельный набор процессов СУБД с общей памятью.
Схема содержится внутри базы данных и является контейнером для таблиц. Кроме того, схема = пользователь.
Таблицы с одинаковыми именами могут существовать одновременно в разных схемах.
Почему не удается определить OCI environment (например, в Attunity)?
Приложение использующее Oracle Client должно каким-то образом его найти. Путь установки Oracle Client добавляется в %PATH% Oracle Installer-ом при установке. Но следует иметь ввиду, что переменные окружения устанавливаются процессу при запуске и, к примеру, Visual Studio (BIDS, Data Tools) запущенная до установки клиента, требует перезапуска, что бы начать использовать новый %PATH%.
Эта ошибка может быть по разному сформулирована в других приложениях.
Как настроить символьную кодировку Oracle Client?
Неверно настроенная кодировка может влиять как на получаемые данные, так и на выполнение запросов. Это может проявляться в том, что REPLACE(table_column, ‘А’, ‘Б’) в одном инструменте работает, а в другом нет, потому, что литералы ‘А’ и ‘Б’, поступающие в БД, воспринимаются иначе в одном из инструментов.
Для 32-х разрядного клиента в реестре в [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE] установите параметр «NLS_LANG»=»RUSSIAN_CIS.CL8MSWIN1251» (типа REG_SZ).
Для 64-х разрядного клиента в реестре в [HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE], аналогично, установите параметр «NLS_LANG»=»RUSSIAN_CIS.CL8MSWIN1251» (типа REG_SZ).
После настройки кодировки необходимо перезагрузиться, поскольку, уже запущенный Oracle Client её не перечитает.