Ассистент Конфигурации базы данных (DBCA). Использование DBCA для Создания Базы данных.
Ассистент Конфигурации Базы данных (DBCA) предлагает несколько вариантов действий с различными операциями. Можно использовать DBCA, чтобы создать, изменить конфигурацию или удалить базу данных. Можно также создать базу данных из списка предопределенных шаблонов или использовать существующую базу данных в качестве образца, чтобы создать новую базу данных или шаблон.
DBCA предоставляет несколько возможностей, чтобы Вы могли создать базу данных, удовлетворяющую Вашим потребностям. DBCA выводит серию страниц, где Вы вводите конфигурационную информацию. На большинстве страниц DBCA предоставляет настройки по умолчанию, которые можно принять, если они допустимы. Шаги, входящие в создание базы данных посредством DBCA, следующие:
Войдите в систему своего компьютера как член группы DBA ОС, которой разрешается устанавливать программное обеспечение Oracle. Если требуется, установите переменные окружения и введите dbca, чтобы вызвать DBCA. Когда появится главная начальная страница, щелкните Next, чтобы продолжить.
Выберите действие, которое Вы хотите выполнить. В данном случае выберите Create a Database и кликните Next, чтобы начать создание БД.
Database Templates: Выберите тип шаблона базы данных, который будет использоваться при создании базы данных. Есть три шаблона базы данных (General Purpose or Transaction Processing, Custom Database и Data Warehouse), которые копируют предварительно сконфигурированную базу данных, включая файлы данных. Эти файлы включают файлы управления, файлы оперативных журналов и файлы данных для различных табличных пространств, присутствующих в БД. Щелкните по Show Details, чтобы просмотреть конфигурацию для каждого типа базы данных. Для более сложных сред можно выбрать опцию Custom Database.
Database Identification: Введите Глобальное Имя базы данных в форме имя_базы_данных.имя_домена, а также системный идентификатор (SID). По умолчанию SID приравнивается к имени базы данных и однозначно определяют экземпляр, связанный с базой данных.
Management Options: Используйте эту страницу, чтобы настроить Вашу базу данных так, чтобы ей можно было управлять из Oracle Enterprise Manager. Выберите значение по умолчанию: “Configure the Database with Enterprise Manager.” Дополнительно, эта страница позволяет Вам сконфигурировать аварийные уведомления и настройки областей ежедневного резервного копирования на диск. Опция Register with Grid Control будет недоступна, если DBCA не может обнаружить агент Управления Гридом Enterprise Manager, с которым он мог бы связаться.
Отметьте: Конфигурирование Enterprise Manager Вашей базы данных требует, чтобы прослушиватель был также сконфигурирован (в нашей учебной среде прослушиватель был сконфигурирован во время установки Инфраструктуры Грида Oracle).
Database Credentials: Используйте эту страницу, чтобы указать пароли для административных учетных записей, таких как SYS и SYSTEM. В учебном занятии используйте oracle_4U в качестве пароля для всех административных учетных записей.
Database File Locations: Определите тип механизма хранения (Автоматическое управление Хранением (ASM) или Файловая система), который Вы хотите использовать для Вашей базы данных. Storage Location выберите согласно своим потребностям. В нашем примере механизмом хранения является ASM, таким образом, используются Управляемые Oracle Файлы (OMF). Кнопка Browse позволяет Вам просмотреть доступные дисковые группы и выбрать наиболее подходящую дисковую группу (+DATA выбирается в примере на слайде). Вас попросят указать пароль ASMSNMP, специфичный для ASM после того, как Вы выберете дисковую группу. Управляемые Файлы Oracle (OMF) могут также использоваться при хранении в файловой системе, избавляя Вас от необходимости непосредственно управлять файлами операционной системы в базе данных Oracle. При желании можно создать дополнительные копии журналов транзакций и управляющих файлов, щелкая по кнопке Multiplex Redo Logs и Control Files. Также имеется кнопка, позволяющая Вам откорректировать переменные расположения файлов: ORACLE_BASE, ORACLE_HOME, DB_NAME, DB_UNIQUE_NAME, SID.
Recovery Configuration: Выберите опции восстановления для Вашей базы данных. Чтобы сконфигурировать мгновенную область восстановления, установите галочку Specify Flash Recovery Area и затем укажите расположение и размер мгновенной области восстановления. В примере, показанном на слайде, в качестве расположения мгновенной области восстановления указывается дисковая группа ASM +FRA, а размер 4452 Мбайта. Рекомендуется, чтобы размер Вашей мгновенной области восстановления был больше чем размер Вашей базы данных. Архивирование и архивирование связанных параметров могут также быть сконфигурированы на этой странице
Отметьте: Мгновенная область восстановления была переименована в быструю область восстановления, но Вы по-прежнему можете встретить ссылки на мгновенную область восстановления в некоторых продуктах Oracle на настоящее время.
Database Content: Эта страница предоставляют возможности для того, чтобы выбрать компоненты (такие как Демонстрационные Схемы) и вкладку, где можно определить любые пользовательские сценарии, которые должны быть выполнены после того, как база данных будет создана.
Initialization Parameters: вкладки на этой странице обеспечивают доступ к страницам, которые позволяют Вам изменить настройки базы данных по умолчанию:
Memory: Используйте эту страницу, чтобы установить параметры инициализации, которые контролируют использование памяти. Используйте либо (A) Typical, либо (B) Custom выделение памяти.
Sizing: Чтобы определить размер блока, введите размер в байтах или примите значение по умолчанию.
Character Sets: Используйте эту страницу, чтобы определить наборы символов для Вашей базы данных.
Подсказка по Передовой практике: Корпорация Oracle рекомендует (всегда, когда это возможно), чтобы Вы использовали Unicode для набора символов базы данных, потому что это обеспечивает оптимальную гибкость для того, чтобы она поддерживала веб-технологии, а так же как множество разговорных языков.
Connection Mode: Выберите один из режимов: Dedicated или Shared Server. Для получения дополнительной информации см. урок «Конфигурируя Сетевой Среды Oracle.”
Просмотрите и измените любые параметры инициализации, нажимая кнопку All Initialization Parameters.
Отметьте: Несколько параметров инициализации устанавливаются на все время жизни базы данных, например DB_BLOCK_SIZE.
Database Storage: Рассмотрите и измените, в случае необходимости, текущие настройки хранения базы данных. Если Вы выбрали один из предварительно сконфигурированных шаблонов для базы данных, Вы не сможете добавить или удалить управляющие файлы или файлы данных.
Create Options: У Вас имеются следующие опции: создать базу данных сейчас, сохранить определение базы данных как шаблон и сгенерировать скрипты создания. Если Вы выбираете все опции и щелкаете по Finish, DBCA сначала сохраняет шаблон базы данных, затем генерирует сценарии в Ваш целевой каталог, и наконец создает Вашу базу данных.
Резюме по Созданию Базы данных
Страница Confirmation появляется после того, как Вы щелкните по Finish, здесь Вы можете просмотреть всю конфигурацию базы данных перед ее созданием. Нажмите OK, чтобы закрыть страницу Confirmation и начать создание базы данных.
Отметьте: Вы можете сохранить описание вашей базы данных в HTML файл, чтобы потом можно было легко к нему вернуться.
Управление паролями
После того как DBCA закончит работу, отметьте следующую информацию на будущее:
Расположение файлов журналов установки
Глобальное имя базы данных
Системный идентификатор (SID)
Имя файла параметров сервера и расположение
URL Консоли Управления Enterprise Manager
Щелкните по Password Management, чтобы разблокировать учетные записи базы данных, которые Вы планируете использовать. Укажите пароли для разблокированных учетных записей. Любые учетные записи, не разблокированные в этот момент, могут быть разблокированы позже при необходимости.
Использование DBCA для создания БД
Процесс создания БД состоит из следующих шагов
В системе Windows также необходим дополнительный шаг, так как в Windows Oracle сервер работает как сервис. Oracle предоставляет дополнительный инструмент oradim.exe в помощь при создании этого сервиса
Эти шаги могут быть последовательно выполнены из SQL *Plus или с помощью специального графического инструмента DBCA (Database Configuration Assistant). Также вы можете написать свои скрипты для этой цели или использовать «тихую» установку.
Наиболее простым способом является создание БД с помощью DBCA. Это мастер-установщик который в режиме диалога запросит необходимые параметры и сделает всё в автоматическом режиме.
DBCA написан на Java и поэтому он выглядит одинаково на всех платформах. На Unix подобных системах вы запускаете DBCA на компьютере где вы хотите создать БД, однако выводить графические интерейс можно на любом компьютере где установлен X сервер для отображения графической информации. Путём установки системной переменной DISPLAY можно перенаправить вывод инфомрации на другое устройство. К примеру команда export DISPLAY=10.10.10.65:0.0 перенаправит информацию на компьютер с етевым адресом 10.10.10.65 вне зависимости от того где реально запущен DBCA.
Для запуска DBCA на Linux вначале необходимо установить системные переменные ORACLE_BASE,ORACLE_HOME,PATH и LD_LIBRARY_PATH. Примерные значения могут быть такими
И запустить приложение вызвав команду dbca.
Помните, что почти все параметры (за исключением одного) можно изменить после создания БД, но это потребует нефункционирования БД.
Если будет установлен Enterprise Manager Database Control, то тогда необходимо выполнить ещё один предварительные шаг; настройка listener-а БД. Это необходимо так как Database Control всегда подключается к БД с помощью listener-а и в процесе установки проверяет наличие хотя бы одного доступного listener-а. Listener можно легко настроить с помощью Net Configuration Assistant (netca).
Скрипты и файлы создаваемые DBCA
DBCA создаёт скрипты и файлы которые находятся в папке ORACLE_BASE/admin/DB_NAME/scripts.
Файл параметров Parameter File
Рассмотрим файл параметров, с именем init.ora. Ниже представлен фрагмент сгенерированного DBCA файла
# Copyright (c) 1991, 2001, 2002 by Oracle Corporation
# Cursors and Library Cache
# Processes and Sessions
# Security and Auditing
# Sort, Hash Joins, Bitmap Indexes
# System Managed Undo and Rollback Segments
Все строки начинающиеся с символа # являются комментариями. Всего доступно около 300 параметров однако DBCA устанавливает значения только для некоторых. Два главных это DB_BLOCK_SIZE и CONTROL_FILES. DB_BLOCK_SIZE устанавливает значение размера буферов в буфере кэша БД (database buffer cache). Так же это значение будет использовано для форматирования файлов данных табличных пространств SYSTEM и SYSAUX. После создания нельзя изменить это значение. CONTROL_FILES являетяс указателем на все копии контрольного файла. В данный момент времени этот файл не существует и значение укажет экзмепляру где создать новый файл. Назначение некоторых других параметров понятно, и все они описаны в документации Oracle. Единственный параметр у которого нет значения по умолчанию – это DB_NAME.
Скрипт создания БД
Ниже представлен скрипт который DBCA выполняет в процессе создания БД (пример для Windows).
Вначале скрипт создаёт несколько папок внутри папки ORACLE_BASE. Далее устанавливаются значения системной переменной ORACLE_SID и добавляется путь ORACLE_HOME/bin к переменной PATH. Две команды которые используют oradim.exe не используются в Linux. В Windows они нужны чтобы настроить запуск экземпляра БД как сервиса.
После скрипт запускает SQL *Plus и выполняется SQL скрипт %DB_NAME%.sql который управляет процессом создания БД
PROMPT specify a password for sys as parameter 1;
DEFINE sysPassword = &1
PROMPT specify a password for system as parameter 2;
DEFINE systemPassword = &2
PROMPT specify a password for sysman as parameter 3;
DEFINE sysmanPassword = &3
PROMPT specify a password for dbsnmp as parameter 4;
DEFINE dbsnmpPassword = &4
Команда CREATE DATABASE
Пример скрипта CreateDB.sql
connect «SYS»/»&&sysPassword» as SYSDBA
startup nomount pfile=»D:\oracle\app\admin\ocp11g\scripts\init.ora»;
CREATE DATABASE «ocp11g»
SIZE 300M REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
EXTENT MANAGEMENT LOCAL
SYSAUX DATAFILE ‘D:\oracle\app\oradata\ocp11g\sysaux01.dbf’
SIZE 120M REUSE AUTOEXTEND ON NEXT 10240K MAXSIZE UNLIMITED
SMALLFILE DEFAULT TEMPORARY TABLESPACE TEMP TEMPFILE
‘D:\oracle\app\oradata\ocp11g\temp01.dbf’ SIZE 20M REUSE
AUTOEXTEND ON NEXT 640K MAXSIZE UNLIMITED
SMALLFILE UNDO TABLESPACE «UNDOTBS1» DATAFILE
‘D:\oracle\app\oradata\ocp11g\undotbs01.dbf’ SIZE 200M REUSE
AUTOEXTEND ON NEXT 5120K MAXSIZE UNLIMITED
CHARACTER SET WE8MSWIN1252
NATIONAL CHARACTER SET AL16UTF16
LOGFILE GROUP 1 (‘D:\oracle\app\oradata\ocp11g\redo01.log’) SIZE 51200K,
GROUP 2 (‘D:\oracle\app\oradata\ocp11g\redo02.log’) SIZE 51200K,
GROUP 3 (‘D:\oracle\app\oradata\ocp11g\redo03.log’) SIZE 51200K
USER SYS IDENTIFIED BY «&&sysPassword»
USER SYSTEM IDENTIFIED BY «&&systemPassword»;
Скрипт подключается к экземпляру, используя авторизацию из файла паролей. Команды echo и spool выводя в лог всё что происходит.
Команда STARTUP NOMOUNT создаёт структуры экземпляр в памяти используя файл параметров. NO MOUNT означает что база данных не будет подключена и открыта. После того как эта команда выполнена – экземпляр существует в памяти и работают фоновые процессы. Размеры SGA установлены согласна файла параметров.
Команда CREATE DATABASE использует имя базы данных и множество параметров. Вначале устанавливаются определенные ограничения для всей БД. Они могут изменять позже, но лучше всего устанавливать допустимые значения сейчас, поскольку их изменение очень трудоёмкая операция. Далее указываются где создать файлы данных для табличных пространств SYSTEM, SYSAUX и UNDO. Также указываются где хранить файлы для временного табличного пространства (TEMPORARY tablespace). Так же указывается кодировка БД для словаря данных и столбцов типа VARCHAR2, CHAR и CLOB. Параметры для файлов логов и т.д. В конце идёт указание на использование паролей из файла паролей и отключение записи в лог.
Этот файл с командой CREATE DATABASE создаст базу данных. После успешного выполнения экзмепляр будет работать в памяти и БД будет создана, включая файлы контроля, файлы данных и файлы логов. Словарь данных будет сгенерирован в табличном пространстве SYSTEM. Однако несмотря на то что БД создана, она пока непригодна для использования. Оставшиеся скрипты, которые вызовет файл %DB_NAME%.sql исправят это. У команды CREATE DATABASE много параметров, однако все они имеют значение по умолчанию. Например если вы не укажете файлы данных для табличного пространства SYSTEM все равно создатся минимум один файл. Для табличных пространств UNDO и TEMPORARY нет значений по умолчанию – но БД может быть создана без них, а потом можно указать эти значения.
Скрипты после создания БД
Остальные скрипты вызываемые %DB_NAME%.sql зависят от выбора в процессе работы с DBCA. В нашем примере был выбран только Enterprise Manager Database Control и поэтому будут запущены только 4 скрипта.
Using DBCA to Create and Configure a Database
During installation, you can direct the installer to create and configure a new database. If you have already done so, you can skip to the next chapter.
However, if you install Oracle software only, or if you want to create additional databases with the release software that you just installed, then you can use the Database Configuration Assistant (DBCA).
DBCA enables you to perform the following tasks:
Starting DBCA
Log on to your computer as a member of the administrative group that is authorized to install Oracle software and create and run the database.
To launch the DBCA on UNIX, or as another method on a Windows operating system, enter the following command at a system prompt:
The Welcome window appears.
Click Next to continue. The DBCA Operations window appears.
Creating a Database with DBCA
On the DBCA Operations window, select Create a Database to start a wizard that enables you to create and configure a database. The wizard requests your input on the following:
Note that most windows of the wizard provide a default setting. To accept all the default parameters, you can click Finish at any step. DBCA displays a final confirmation window. Click OK to initiate the database creation.
Database Templates
The templates contain settings optimized for workload. Click Show Details to see the configuration for each type of database. Choose the template suited to the type of workload your database will support. If you are not sure which to choose, select the default General Purpose template.
For more complex environments, you can select the Custom Database option. This option results in a more extensive interview, which means that it will take longer to create your database because a database creation script must be run.
For more information about using database templates, see «Managing Templates with DBCA».
Database Identification
In the SID box, enter the Oracle system identifier. The SID defaults to the database name and uniquely identifies the instance that runs the database.
Management Options
Use this window to set up your database so it can be managed with Oracle Enterprise Manager. Oracle Enterprise Manager provides Web-based management tools for individual databases, as well as central management tools for managing your entire Oracle environment.
Check Configure the Database with Enterprise Manager to use Enterprise Manager. Select one of the following options:
Select Use Database Control for Database Management to manage your database locally. If you choose this option, you can additionally check Enable Email Notifications for Oracle to e-mail you alerts regarding potential problems, and check Enable Daily Backup. Click Help for more information about these options.
Database Credentials
Select Use the Same Password for All Accounts and enter the password to use the same password for all accounts.
Select Use Different Passwords and specify passwords individually.
Storage Options
Database File Locations
In this window, you specify the Oracle home and directory path in which to install the Oracle software. Choose one of the following:
Use Database File Locations from Template —Selecting this option instructs the DBCA to use the directory information as specified in the template. Later, you can make modifications to database filenames and locations.
Use Common Location for All Database Files —This option requires you to specify a new directory for the Oracle home. All the database files will be created in this location. Later, you can make modifications to database filenames and locations.
Use Oracle-Managed Files —Select this option to have Oracle directly manage operating system files comprising an Oracle database. You specify default location called a database area for all your files. Oracle thereafter automatically creates and deletes files in this location as required. You can also create multiple copies of your redo and online log files by selecting Multiplex Redo Logs and Control Files. To learn more about redo logs and control files, refer to Chapter 9, «Performing Backup and Recovery».
Selecting this option enables you to delegate the complete management of database files to the database. You no longer need to specify the filenames, location, or their sizes.
Recovery Configuration
When you create a new database, it is important to configure the database so you can recover your data in the event of a system failure. You can select the following options:
Specify Flash Recovery Area —Select this option to specify a backup and recovery area and specify its directory location and size. You can use variables to identify standard locations. To review or add additional locations, click File Location Variables at the bottom of the window.
Database Content
When you create your database, you can load it with data.
Check Sample Schemas to include the Sample Schemas ( EXAMPLE ) tablespace in your database. The Sample Schemas provide a common platform for examples. Oracle books and educational materials contain examples based upon the Sample Schemas. Oracle recommends they be included in your database.
In the Custom Scripts tab, you can specify one or more SQL scripts to run after your database is created. Scripts are useful for performing post-installation tasks, such as loading custom schemas. To specify scripts, check Run the following scripts; otherwise accept the default No scripts to run. Note that if you choose to run scripts after installation, your scripts must include a connect string that identifies the database. Click Help for more information.
Initialization Parameters
The links on this window provide access to windows that enable you change default initialization parameter settings. These parameters fall into the following categories:
Memory
Use this window to set the initialization parameters that control how the database manages its memory usage. You can choose from one of the following approaches to memory management:
Typical —This method requires little configuration, and allocates memory as a percentage of total overall physical system memory. Select Typical and enter a percentage value. Click Show Memory Distribution to see how much memory the DBCA assigns to the System Global Area (SGA) and the Program Global Area (PGA). To learn more about PGA and SGA, refer to «Managing Memory Parameters» in Chapter 5, «Managing the Oracle Instance».
Custom —This method requires more configuration, but gives you more control over how the database uses system memory. This option is meant for more experienced database administrators. You can directly specify memory sizes for the SGA and PGA and their sub-structures, such as the shared pool and buffer cache.
Select one of the following options:
Select Automatic to allocate specific amounts of memory to SGA and PGA.
Select Manual to enter specific values for each SGA component. This will customize how the SGA memory is distributed among the SGA memory substructures.
Sizing
In th is tab, you specify the smallest block size and the maximum number of operating system user processes that can simultaneously connect to the database.
In the Block Size list, enter the size in bytes or accept the default. Oracle Database data is stored in these blocks. One data block corresponds to a specific number of bytes of physical space on disk. While using pre-defined templates, this field is not enabled since the database will be created with the default block size of 8 KB. But while using the custom option, you can change block size. Selecting a block size other than the default 8 KB value requires advanced knowledge and should only be done when absolutely required.
In the Processes field, specify the maximum number of processes that can simultaneously connect to the database. Enter a number or accept the default of 150. The default value for this parameter is good enough for many environments.The value should be 6 or greater. This value should allow for all background processes, such as locks and parallel execution processes.
Character Sets
U se this window to define the character sets used by your database. Character sets are the encoding schemes used to display characters on your computer screen. Choosing a character set determines what languages can be represented in the database.
Use the Default— Select this option if you need to support only the language currently used by the operating system for all your database users and your database applications.
Use Unicode (AL32UTF8) —Select this option if you need to support multiple languages for your database users and your database applications.
Choose from the list of character sets— Select this option if you want the Oracle Database to use a character set other than the default character set used by the operating system.
In the National Character Set list, select a character set or accept the default. The national character set is an alternative character set that enables you to store Unicode characters in a database that does not have a Unicode database character set. Choosing a national character can make programming in the national character set easier.
In the Default Language list, select a default database language or accept the default. The default language determines how the database supports locale-sensitive information such as day and month abbreviations, default sorting sequence for character data, and writing direction (left or right).
In the Default Date Format list, select a date format or accept the default. The default date format determines the convention for displaying the hour, day, month, and year. For example, in the United Kingdom, the date format is DD-MM-YYYY.
Connection Mode
Us e this window to select the database mode. You can run the database in either of the following modes:
Dedicated Server Mode allows a dedicated server process for each user process. Select this option when the number of total clients is expected to be small, or when database clients will make persistent, long-running requests to the database.
Shared Server Mode allows several client connections to share a database-allocated pool of resources. Use this mode when a large number of users need to connect to the database. It is also useful when database memory is limited or when better performance is needed, because you can have more client connections to the database than in dedicated server mode. If you choose shared server mode, then you must also indicate the number of server processes you want to create when an instance is started. For more information about setting this parameter, click Help.
Database Storage
Note that if you selected one of the preconfigured templates for a database, then you cannot add or remove control files, datafiles, or undo segments.
Database Creation Options
Check any of the following options for creating the database:
Create Database —Check to create your database at this time.
Save as a Database Template —Check to save the database definition as a template to use at another time.
Generate Database Creation Scripts —Check to generate a SQL database creation script that you can run at a later time.
Configuring Database Options with DBCA
In the Operations window, select Configure Database Options to change various aspects of your database configuration. For example, you can change the database from a dedicated server to a shared server. You can add database options that have not been previously configured for use with your database, for example, Oracle Label Security or Oracle OLAP.
Deleting a Database with DBCA
In the Operations window, select Delete a Database to remove a database from the system. When you select this option, DBCA deletes all the files associated with this database. On Windows, any associated services are also deleted.
Managing Templates with DBCA
DBCA templates are XML files that contain information required to create a database. Templates are used in DBCA to create new databases and clone existing databases. The information in templates includes database options, initialization parameters, and storage attributes (for datafiles, tablespaces, control files, and online redo logs).
Templates can be used just like scripts, but they are more powerful than scripts because you have the option of cloning a database. Cloning saves time by copying a seed database’s files to the correct locations.
Templates are stored in the following directory:
Advantages of Using Templates
Using templates has the following advantages:
Time saving. If you use a template you do not have to define the database.
Easy Duplication. By creating a template containing your database settings, you can easily create a duplicate database without specifying parameters twice.
Easy editing. You can quickly change database options from the template settings.
Easy sharing. Templates can be copied from one machine to another.
Types of Templates
Templates are divided into the following types:
The characteristics of each are shown in Table 2-1.
Table 2-1 DBCA Template Types
| Type | File Extension | Includes Datafiles | Database Structure |
|---|---|---|---|
| Environment | Description of Environment |
|---|---|












