Oracle создать пользователя и схему
Use the CREATE USER statement to create and configure a database user , which is an account through which you can log in to the database, and to establish the means by which Oracle Database permits access by the user.
You can issue this statement in an Oracle Automatic Storage Management (Oracle ASM) cluster to add a user and password combination to the password file that is local to the Oracle ASM instance of the current node. Each node's Oracle ASM instance can use this statement to update its own password file. The password file itself must have been created by the ORAPWD utility.
You can enable a user to connect to the database through a proxy application or application server. For syntax and discussion, refer to ALTER USER.
You must have the CREATE USER system privilege. When you create a user with the CREATE USER statement, the user's privilege domain is empty. To log on to Oracle Database, a user must have the CREATE SESSION system privilege. Therefore, after creating a user, you should grant the user at least the CREATE SESSION system privilege. Refer to GRANT for more information.
Only a user authenticated AS SYSASM can issue this command to modify the Oracle ASM instance password file.
To specify the CONTAINER clause, you must be connected to a multitenant container database (CDB). To specify CONTAINER = ALL , the current container must be the root. To specify CONTAINER = CURRENT , the current container must be a pluggable database (PDB).
Specify the name of the user to be created. This name can contain only characters from your database character set and must follow the rules described in the section "Database Object Naming Rules" . Oracle recommends that the user name contain at least one single-byte character regardless of whether the database character set also contains multibyte characters.
In a CDB, the requirements for a user name are as follows:
Oracle recommends that user names and passwords be encoded in ASCII or EBCDIC characters only, depending on your platform.
The IDENTIFIED clause lets you indicate how Oracle Database authenticates the user.
Oracle Database Security Guide for more information about case-sensitive passwords, password complexity, and other password guidelines
Passwords must follow the rules described in the section "Database Object Naming Rules" , unless you are using one of the three Oracle Database password complexity verification routines. These routines requires a more complex combination of characters than the normal naming rules permit. You implement these routines with the UTLPWDMG.SQL script, which is further described in Oracle Database Security Guide .
Oracle recommends that user names and passwords be encoded in ASCII or EBCDIC characters only, depending on your platform.
Oracle Database Security Guide to for a detailed discussion of password management and protection
You cannot specify this clause for external or global users.
Specify EXTERNALLY to create an external user. Such a user must be authenticated by an external service, such as an operating system or a third-party service. In this case, Oracle Database relies on authentication by the operating system or third-party service to ensure that a specific external user has access to a specific database user.
This clause is required for and used for SSL-authenticated external users only. The certificate_DN is the distinguished name in the user's PKI certificate in the user's wallet. The maximum length of certificate_DN is 1024 characters.
This clause is required for and used for Kerberos-authenticated external users only. The maximum length of kerberos_principal_name is 1024 characters.
Oracle strongly recommends that you do not use IDENTIFIED EXTERNALLY with operating systems that have inherently weak login security.
Restriction on Creating External Users
Oracle ASM does not support the creation of external users.
The GLOBALLY clause lets you create a global user . Such a user must be authorized by the enterprise directory service (Oracle Internet Directory).
The directory_DN string can take one of two forms:
The X.509 name at the enterprise directory service that identifies this user. It should be of the form CN= username,other_attributes , where other_attributes is the rest of the user's distinguished name (DN) in the directory. This form uses the LDAP Data Interchange Format (LDIF) and creates a private global schema .
A null string (' ') indicating that the enterprise directory service will map authenticated global users to this database schema with the appropriate roles. This form is the same as specifying the GLOBALLY keyword alone and creates a shared global schema .
The maximum length of directory_DN is 1024 characters.
You can control the ability of an application server to connect as the specified user and to activate that user's roles using the ALTER USER statement.
Restriction on Creating Global Users
Oracle ASM does not support the creation of global users.
Oracle Database Security Guide for more information on global users
NO AUTHENTICATION Clause
Use the NO AUTHENTICATION clause to create a schema that does not have a password and cannot be logged into. This is intended for schema only accounts and reduces maintenance by removing default passwords and any requirement to rotate the password.
DEFAULT COLLATION Clause
This clause lets you specify the default collation for the schema owned by the user. The default collation is assigned to tables, views, and materialized views that are subsequently created in the schema.
For collation_name , specify a valid named collation or pseudo-collation.
If you omit this clause, then the default collation for the schema owned by the user is set to the USING_NLS_COMP pseudo-collation.
You can override this clause and assign a different default collation to a particular table, materialized view, or view by specifying the DEFAULT COLLATION clause of the CREATE or ALTER statement for the table, materialized view, or view. You can also override the default collations of all schemas for the duration of a database session by setting the default collation for the session. See the DEFAULT_COLLATION clause of ALTER SESSION for more details.
You can specify the DEFAULT COLLATION clause only if the COMPATIBLE initialization parameter is set to 12.2 or greater, and the MAX_STRING_SIZE initialization parameter is set to EXTENDED .
DEFAULT TABLESPACE Clause
Specify the default tablespace for objects that are created in the user's schema. If you omit this clause, then the user's objects are stored in the database default tablespace. If no default tablespace has been specified for the database, then the user's objects are stored in the SYSTEM tablespace.
Restriction on Default Tablespaces
You cannot specify a locally managed temporary tablespace, including an undo tablespace, or a dictionary-managed temporary tablespace, as a user's default tablespace.
CREATE TABLESPACE for more information on tablespaces in general and undo tablespaces in particular
Oracle Database Security Guide for more information on assigning default tablespaces to users
[LOCAL] TEMPORARY TABLESPACE Clause
Specify the tablespace or tablespace group for the user's temporary segments. If you omit this clause, then the user's temporary segments are stored in the database default temporary tablespace or, if none has been specified, in the SYSTEM tablespace.
Specify tablespace to indicate the user's temporary tablespace. Specify TEMPORARY TABLESPACE to indicate a shared temporary tablespace. Specify LOCAL TEMPORARY TABLESPACE to indicate a local temporary tablespace. If you are connected to a CDB, then you can specify CDB$DEFAULT to use the CDB-wide default temporary tablespace.
Specify tablespace_group_name to indicate that the user can save temporary segments in any tablespace in the tablespace group specified by tablespace_group_name . Local temporary tablespaces cannot be part of a tablespace group.
Restrictions on Temporary Tablespace
This clause is subject to the following restrictions:
The tablespace must be a temporary tablespace and must have a standard block size.
The tablespace cannot be an undo tablespace or a tablespace with automatic segment-space management.
Oracle Database Administrator's Guide for information about tablespace groups and Oracle Database Security Guide for information on assigning temporary tablespaces to users
CREATE TABLESPACE for more information on undo tablespaces and segment management
Use the QUOTA clause to specify the maximum amount of space the user can allocate in the tablespace.
A CREATE USER statement can have multiple QUOTA clauses for multiple tablespaces.
UNLIMITED lets the user allocate space in the tablespace without bound.
The maximum amount of space that you can specify is 2 terabytes (TB). If you need more space, then specify UNLIMITED .
Restriction on the QUOTA Clause
You cannot specify this clause for a temporary tablespace.
size_clause for information on that clause and Oracle Database Security Guide for more information on assigning tablespace quotas
Specify the profile you want to assign to the user. The profile limits the amount of database resources the user can use. If you omit this clause, then Oracle Database assigns the DEFAULT profile to the user.
Oracle recommends that you use the Database Resource Manager rather SQL profiles to establish database resource limits. The Database Resource Manager offers a more flexible means of managing and tracking resource use. For more information on the Database Resource Manager, refer to Oracle Database Administrator's Guide.
PASSWORD EXPIRE Clause
Specify PASSWORD EXPIRE if you want the user's password to expire. This setting forces the user or the DBA to change the password before the user can log in to the database.
Specify ACCOUNT LOCK to lock the user's account and disable access. Specify ACCOUNT UNLOCK to unlock the user's account and enable access to the account. The default is ACCOUNT UNLOCK .
This clause is not reversible. Specify ENABLE EDITIONS to allow the user to create multiple versions of editionable objects in this schema using editions. Editionable objects in schemas that are not editions-enabled cannot be editioned.
Note the following before enabling editions with ALTER USER :
Enabling editions is not a live operation.
When a database is upgraded from Release 11.2 to Release 12.1, users who were enabled for editions in the pre-upgrade database are enabled for editions in the post-upgrade database and the default schema object types are editionable in their schemas. The default schema object types are displayed by the static data dictionary view DBA_EDITIONED_TYPES . Users who were not enabled for editions in the pre-upgrade database are not enabled for editions in the post-upgrade database and no schema object types are editionable in their schemas.
To see which users already have editions enabled, see the EDITIONS_ENABLED column of the static data dictionary view DBA_USERS or USER_USERS .
Restriction on Enabling Editions
The FOR clause is ignored when used with ENABLE EDITIONS . This only applies to the CREATE USER statement, not the ALTER USER statement.
You cannot enable editions for any schemas supplied by Oracle except for the sample schemas in the seed database.
Oracle Database Reference for more information about the V$EDITIONABLE_TYPES dynamic performance view
The CONTAINER clause applies when you are connected to a CDB. However, it is not necessary to specify the CONTAINER clause because its default values are the only allowed values.
To create a common user, you must be connected to the root. You can optionally specify CONTAINER = ALL , which is the default when you are connected to the root.
To create a local user, you must be connected to a PDB. You can optionally specify CONTAINER = CURRENT , which is the default when you are connected to a PDB.
While creating a common user, any default tablespace, temporary tablespace, or profile specified using the following clauses must exist in all the containers belonging to the CDB:
If these objects do not exist in all the containers, the CREATE USER statement fails.
All of the following examples use the example tablespace, which exists in the seed database and is accessible to the sample schemas.
Creating a Database User: Example
If you create a new user with PASSWORD EXPIRE , then the user's password must be changed before the user attempts to log in to the database. You can create the user sidney by issuing the following statement:
The user sidney has the following characteristics:
The password out_standing1
Default tablespace example , with a quota of 10 megabytes
Temporary tablespace temp
Access to the tablespace SYSTEM , with a quota of 5 megabytes
Limits on database resources defined by the profile app_user (which was created in "Creating a Profile: Example" )
An expired password, which must be changed before sidney can log in to the database
Creating External Database Users: Examples
The following example creates an external user, who must be identified by an external source before accessing the database:
The user app_user1 has the following additional characteristics:
Default tablespace example
Default temporary tablespace example
5M of space on the tablespace example and unlimited quota on the temporary tablespace of the database
Limits on database resources defined by the app_user profile
To create another user accessible only by an operating system account, prefix the user name with the value of the initialization parameter OS_AUTHENT_PREFIX . For example, if this value is " ops$ ", then you can create the externally identified user external_user with the following statement:
Creating a Global Database User: Example
The following example creates a global user. When you create a global user, you can specify the X.509 name that identifies this user at the enterprise directory server:
Creating a Common User in a CDB
Думаю, настало время разобраться с тем как же создаются "схемы" в БД Oracle. Под понятием схема имеется ввиду сам созданный аккаунт или говоря прямо - пользователь БД! Целью создания пользователя как раз и является получение схемы БД, с определенными правами и привилегиями. Создание пользователя в БД Oracle достаточно не сложный, но в тоже время довольно концептуальный момент. Для создания пользователя (схемы), применяется команда DDL - CREATE USER. Она имеет следующий синтаксис:
- [пользователь] [Username] - Имя пользователя (название схемы).
- [пароль] [Password] - Пароль для учетной записи.
- DEFAULT TABLESPACE - Табличное пространство в котором будут находиться создаваемые в данной схеме объекты. Эта настройка не дает пользователю права создавать объекты - здесь устанавливается только значение по умолчанию.
- TEMPORARY TABLESPACE - Табличное пространство, в котором находятся временные сегменты, используемые в процессе сортировки транзакций.
- QUOTA - Позволяет пользователю сохранять объекты в указанном табличном пространстве, занимая там место вплоть до определенного в квоте общего размера.
К слову сказать, в чем мы далее и убедимся. Для того, чтобы запросы пользователей могли создавать временные сегменты в табличном пространстве TEMP, им не нужны квоты на дисковое пространство. Попробуем создать пользователя! Запускайте SQL*Plus с пользователем SYS или SYSTEM пароли администраторов смотрите в шаге 5! Из всего выше сказанного, запишем вот такую конструкцию:
Здесь мы создаем пользователя (схему) DUMMY с паролем DUMB и позволяем ему резвится на 100 Мб пространства USERS и еще немного выделяем из пространства TEMP. Получаем в результате:
Ок! Пользователь (схема) создан. Наверное, можно уже подключится и начать создавать объекты! Пробуем!
Именное такой синтаксис подключения можно использовать, он еще называется строка коннекта и расписывается вот так:
Опа! Не повезло! Создание пользователя - это еще не все! Теперь ему нужно разрешить самое основное - создавать сессию с сервером. Сделать это можно командой GRANT. Она достаточно объемная и мы ей займемся чуть позже, а пока восстановим подключение:
Даем пользователю право создавать сессию с сервером:
Вот теперь можно немного перевести дух. Итак, мы создали пользователя, определили ему табличные пространства, назначили квоты на них. И даже позволили создавать сессию с сервером. Давайте убедимся, что пользователь создан и чувствует себя нормально. Производим переконнект на админа БД:
Дадим такой запрос к представлению DBA_USERS:
Кто знаком с криптографией, может на досуге раскусить - E888ADB4D5FFE1B2 или хотя бы провести аналогию с DUMB! Итак, все с нашей схемой в порядке! Осталось только разрешить пользователю создавать объекты БД.
Да, так как оператор GRANT это DDL, то COMMIT вызывается не явно! В данном случае мы разрешили пользователю, создавать такие основные объекты БД как - TABLE, PROCEDURE, TRIGGER, VIEW, SEQUENCE. Для начала этого достаточно. А что делать, если пользователю будет необходимо изменять эти объекты? Тогда нужно добавить еще немного прав, на изменение (ALTER) вот так:
Вот теперь он может не только создавать эти объекты, но и изменять их! А, что если пользователю необходимо будет удалить какой-либо объект или удалить записи из таблиц? Тогда нужно добавить права на удаление объектов БД вот так:
Уфф! Ну вот теперь кажется все! Пользователь действительно полноценный и может работать! Помните в шаге 6 мы с вами это уже проделывали, но тогда я не вдавался в подробности, так как было не до того! А, вот теперь давайте разберемся более детально и продолжим далее.
Создание схемы в Oracle, поначалу может показаться немного запутанной. Вы можете подумать, что оператор CREATE SCHEMA создаст вашу схему, но это не так. Оператор CREATE SCHEMA используется только для создания объектов (т.е. таблиц, представлений и т.д.) в вашей схеме в одном SQL - предложении, но фактически не создает саму схему.
Чтобы создать схему в Oracle, вам необходимо выполнить следующие действия:
5. Создание синонимов для объектов
В качестве последнего шага вам может понадобиться создать синонимы, чтобы другие схемы могли обращаться к новым объектам базы данных (т.е. таблицам) без необходимости префикса имен объектов с именем схемы.
Например, если бы вы были другим пользователем с именем samvel и хотели выбрать из таблицы suppliers в схеме new_schema , вам нужно было бы запустить следующий оператор SELECT (до создания любых синонимов):
Oracle оператор CREATE USER создает учетную запись базы данных, которая позволяет войти в базу данных Oracle.
Пример
Если вы хотите, выполнить простой оператор CREATE USER, который создаст нового пользователя и назначит пароль, вы можете сделать следующее:
Use the CREATE USER statement to create and configure a database user , which is an account through which you can log in to the database, and to establish the means by which Oracle Database permits access by the user.
You can issue this statement in an Oracle Automatic Storage Management (Oracle ASM) cluster to add a user and password combination to the password file that is local to the Oracle ASM instance of the current node. Each node's Oracle ASM instance can use this statement to update its own password file. The password file itself must have been created by the ORAPWD utility.
You can enable a user to connect to the database through a proxy application or application server. For syntax and discussion, refer to ALTER USER.
You must have the CREATE USER system privilege. When you create a user with the CREATE USER statement, the user's privilege domain is empty. To log on to Oracle Database, a user must have the CREATE SESSION system privilege. Therefore, after creating a user, you should grant the user at least the CREATE SESSION system privilege. Refer to GRANT for more information.
Only a user authenticated AS SYSASM can issue this command to modify the Oracle ASM instance password file.
To specify the CONTAINER clause, you must be connected to a multitenant container database (CDB). To specify CONTAINER = ALL , the current container must be the root. To specify CONTAINER = CURRENT , the current container must be a pluggable database (PDB).
Specify the name of the user to be created. This name can contain only characters from your database character set and must follow the rules described in the section "Database Object Naming Rules" . Oracle recommends that the user name contain at least one single-byte character regardless of whether the database character set also contains multibyte characters.
A multitenant container database is the only supported architecture in Oracle Database 20c. While the documentation is being revised, legacy terminology may persist. In most cases, "database" and "non-CDB" refer to a CDB or PDB, depending on context. In some contexts, such as upgrades, "non-CDB" refers to a non-CDB from a previous release.
In a CDB, the requirements for a user name are as follows:
Oracle recommends that user names and passwords be encoded in ASCII or EBCDIC characters only, depending on your platform.
The IDENTIFIED clause lets you indicate how Oracle Database authenticates the user.
Oracle Database Security Guide for more information about case-sensitive passwords, password complexity, and other password guidelines
Passwords must follow the rules described in the section "Database Object Naming Rules" , unless you are using one of the three Oracle Database password complexity verification routines. These routines requires a more complex combination of characters than the normal naming rules permit. You implement these routines with the UTLPWDMG.SQL script, which is further described in Oracle Database Security Guide .
Oracle recommends that user names and passwords be encoded in ASCII or EBCDIC characters only, depending on your platform.
Oracle Database Security Guide to for a detailed discussion of password management and protection
You cannot specify this clause for external or global users.
Specify EXTERNALLY to create an external user. Such a user must be authenticated by an external service, such as an operating system or a third-party service. In this case, Oracle Database relies on authentication by the operating system or third-party service to ensure that a specific external user has access to a specific database user.
This clause is required for and used for SSL-authenticated external users only. The certificate_DN is the distinguished name in the user's PKI certificate in the user's wallet. The maximum length of certificate_DN is 1024 characters.
This clause is required for and used for Kerberos-authenticated external users only. The maximum length of kerberos_principal_name is 1024 characters.
Oracle strongly recommends that you do not use IDENTIFIED EXTERNALLY with operating systems that have inherently weak login security.
Restriction on Creating External Users
Oracle ASM does not support the creation of external users.
The GLOBALLY clause lets you create a global user . Such a user must be authorized by the enterprise directory service (Oracle Internet Directory).
The directory_DN string can take one of two forms:
The X.509 name at the enterprise directory service that identifies this user. It should be of the form CN= username,other_attributes , where other_attributes is the rest of the user's distinguished name (DN) in the directory. This form uses the LDAP Data Interchange Format (LDIF) and creates a private global schema .
A null string (' ') indicating that the enterprise directory service will map authenticated global users to this database schema with the appropriate roles. This form is the same as specifying the GLOBALLY keyword alone and creates a shared global schema .
The maximum length of directory_DN is 1024 characters.
You can control the ability of an application server to connect as the specified user and to activate that user's roles using the ALTER USER statement.
Restriction on Creating Global Users
Oracle ASM does not support the creation of global users.
Oracle Database Security Guide for more information on global users
NO AUTHENTICATION Clause
Use the NO AUTHENTICATION clause to create a schema that does not have a password and cannot be logged into. This is intended for schema only accounts and reduces maintenance by removing default passwords and any requirement to rotate the password.
DEFAULT COLLATION Clause
This clause lets you specify the default collation for the schema owned by the user. The default collation is assigned to tables, views, and materialized views that are subsequently created in the schema.
For collation_name , specify a valid named collation or pseudo-collation.
If you omit this clause, then the default collation for the schema owned by the user is set to the USING_NLS_COMP pseudo-collation.
You can override this clause and assign a different default collation to a particular table, materialized view, or view by specifying the DEFAULT COLLATION clause of the CREATE or ALTER statement for the table, materialized view, or view. You can also override the default collations of all schemas for the duration of a database session by setting the default collation for the session. See the DEFAULT_COLLATION clause of ALTER SESSION for more details.
You can specify the DEFAULT COLLATION clause only if the COMPATIBLE initialization parameter is set to 12.2 or greater, and the MAX_STRING_SIZE initialization parameter is set to EXTENDED .
DEFAULT TABLESPACE Clause
Specify the default tablespace for objects that are created in the user's schema. If you omit this clause, then the user's objects are stored in the database default tablespace. If no default tablespace has been specified for the database, then the user's objects are stored in the SYSTEM tablespace.
Restriction on Default Tablespaces
You cannot specify a locally managed temporary tablespace, including an undo tablespace, or a dictionary-managed temporary tablespace, as a user's default tablespace.
CREATE TABLESPACE for more information on tablespaces in general and undo tablespaces in particular
Oracle Database Security Guide for more information on assigning default tablespaces to users
[LOCAL] TEMPORARY TABLESPACE Clause
Specify the tablespace or tablespace group for the user's temporary segments. If you omit this clause, then the user's temporary segments are stored in the database default temporary tablespace or, if none has been specified, in the SYSTEM tablespace.
Specify tablespace to indicate the user's temporary tablespace. Specify TEMPORARY TABLESPACE to indicate a shared temporary tablespace. Specify LOCAL TEMPORARY TABLESPACE to indicate a local temporary tablespace. If you are connected to a CDB, then you can specify CDB$DEFAULT to use the CDB-wide default temporary tablespace.
Specify tablespace_group_name to indicate that the user can save temporary segments in any tablespace in the tablespace group specified by tablespace_group_name . Local temporary tablespaces cannot be part of a tablespace group.
Restrictions on Temporary Tablespace
This clause is subject to the following restrictions:
The tablespace must be a temporary tablespace and must have a standard block size.
The tablespace cannot be an undo tablespace or a tablespace with automatic segment-space management.
Oracle Database Administrator's Guide for information about tablespace groups and Oracle Database Security Guide for information on assigning temporary tablespaces to users
CREATE TABLESPACE for more information on undo tablespaces and segment management
Use the QUOTA clause to specify the maximum amount of space the user can allocate in the tablespace.
A CREATE USER statement can have multiple QUOTA clauses for multiple tablespaces.
UNLIMITED lets the user allocate space in the tablespace without bound.
The maximum amount of space that you can specify is 2 terabytes (TB). If you need more space, then specify UNLIMITED .
Restriction on the QUOTA Clause
You cannot specify this clause for a temporary tablespace.
size_clause for information on that clause and Oracle Database Security Guide for more information on assigning tablespace quotas
Specify the profile you want to assign to the user. The profile limits the amount of database resources the user can use. If you omit this clause, then Oracle Database assigns the DEFAULT profile to the user.
You can use the CREATE USER statement to create a new user, and associate the user with a profile that has the PASSWORD_ROLLOVER_TIME configured.
You must first set the password rollover period using CREATE PROFILE or ALTER PROFILE .
In the example u1 is the user, with password p1 . prof1 is the profile with PASSWORD_ROLLOVER_TIME set.
Oracle recommends that you use the Database Resource Manager to establish database resource limits rather than SQL profiles. The Database Resource Manager offers a more flexible means of managing and tracking resource use. For more information on the Database Resource Manager, refer to Oracle Database Administrator's Guide.
PASSWORD EXPIRE Clause
Specify PASSWORD EXPIRE if you want the user's password to expire. This setting forces the user or the DBA to change the password before the user can log in to the database.
Specify ACCOUNT LOCK to lock the user's account and disable access. Specify ACCOUNT UNLOCK to unlock the user's account and enable access to the account. The default is ACCOUNT UNLOCK .
This clause is not reversible. Specify ENABLE EDITIONS to allow the user to create multiple versions of editionable objects in this schema using editions. Editionable objects in schemas that are not editions-enabled cannot be editioned.
Note the following before enabling editions with ALTER USER :
Enabling editions is not a live operation.
When a database is upgraded from Release 11.2 to Release 12.1, users who were enabled for editions in the pre-upgrade database are enabled for editions in the post-upgrade database and the default schema object types are editionable in their schemas. The default schema object types are displayed by the static data dictionary view DBA_EDITIONED_TYPES . Users who were not enabled for editions in the pre-upgrade database are not enabled for editions in the post-upgrade database and no schema object types are editionable in their schemas.
To see which users already have editions enabled, see the EDITIONS_ENABLED column of the static data dictionary view DBA_USERS or USER_USERS .
Restriction on Enabling Editions
The FOR clause is ignored when used with ENABLE EDITIONS . This only applies to the CREATE USER statement, not the ALTER USER statement.
You cannot enable editions for any schemas supplied by Oracle.
Oracle Database Reference for more information about the V$EDITIONABLE_TYPES dynamic performance view
The CONTAINER clause applies when you are connected to a CDB. However, it is not necessary to specify the CONTAINER clause because its default values are the only allowed values.
To create a common user, you must be connected to the root. You can optionally specify CONTAINER = ALL , which is the default when you are connected to the root.
To create a local user, you must be connected to a PDB. You can optionally specify CONTAINER = CURRENT , which is the default when you are connected to a PDB.
While creating a common user, any default tablespace, temporary tablespace, or profile specified using the following clauses must exist in all the containers belonging to the CDB:
If these objects do not exist in all the containers, the CREATE USER statement fails.
All of the following examples use the example tablespace, which exists in the seed database and is accessible to the sample schemas.
Creating a Database User: Example
If you create a new user with PASSWORD EXPIRE , then the user's password must be changed before the user attempts to log in to the database. You can create the user sidney by issuing the following statement:
The user sidney has the following characteristics:
The password out_standing1
Default tablespace example , with a quota of 10 megabytes
Temporary tablespace temp
Access to the tablespace SYSTEM , with a quota of 5 megabytes
Limits on database resources defined by the profile app_user (which was created in "Creating a Profile: Example" )
An expired password, which must be changed before sidney can log in to the database
Creating External Database Users: Examples
The following example creates an external user, who must be identified by an external source before accessing the database:
The user app_user1 has the following additional characteristics:
Default tablespace example
Default temporary tablespace example
5M of space on the tablespace example and unlimited quota on the temporary tablespace of the database
Limits on database resources defined by the app_user profile
To create another user accessible only by an operating system account, prefix the user name with the value of the initialization parameter OS_AUTHENT_PREFIX . For example, if this value is " ops$ ", then you can create the externally identified user external_user with the following statement:
Creating a Global Database User: Example
The following example creates a global user. When you create a global user, you can specify the X.509 name that identifies this user at the enterprise directory server:
Creating a Common User in a CDB
2. Назначение привилегий SYSTEM новому пользователю в Oracle
Следующим шагом в настройке вашей схемы является назначение «системных привилегий» новому пользователю samvel .
Эти «системные привилегии» позволят нашему новому пользователю создавать сессию в Oracle, а также создавать таблицы, представления, триггеры, процедуры, последовательности и синонимы в новой схеме. Вот пример того, как мы можем предоставить эти системные привилегии:
Эти новые привилегии теперь предоставляются пользователю, называемому samvel .
3. Создание объектов в схеме
Теперь, когда схема (называемая samvel ) была создана с необходимыми привилегиями, вы можете создавать объекты в схеме. Это можно сделать одним из двух способов:
- Выполнение отдельных операторов SQL для создания каждого объекта. Это будет сделано с помощью операторов CREATE TABLE и CREATE VIEW.
- Выполнение оператора CREATE SCHEMA для создания нескольких объектов в одном выражении SQL.
Синтаксис
Синтаксис оператора CREATE USER в Oracle/PLSQL:
CREATE USER user_name
IDENTIFIED < BY password
| EXTERNALLY [ AS 'certificate_DN' ]
| GLOBALLY [ AS '[ directory_DN ]' ]
>
[ DEFAULT TABLESPACE tablespace
| TEMPORARY TABLESPACE
< tablespace | tablespace_group >
| QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED >
ON tablespace
[ QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED >
ON tablespace
]
| PROFILE profile_name
| PASSWORD EXPIRE
| ACCOUNT < LOCK | UNLOCK >
[ DEFAULT TABLESPACE tablespace
| TEMPORARY TABLESPACE
< tablespace | tablespace_group >
| QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED >
ON tablespace
[ QUOTA integer [ K | M | G | T | P | E ]
| UNLIMITED >
ON tablespace
]
| PROFILE profile
| PASSWORD EXPIRE
| ACCOUNT < LOCK | UNLOCK >]
] ;
1. Создать нового пользователя в Oracle.
По сути, схема создается в Oracle при создании пользователя. (Изучите синтаксис оператора CREATE USER).
Мы можем создать нового пользователя с оператором CREATE USER следующим образом:
Этот оператор CREATE USER создаст нового пользователя samvel в базе данных Oracle, чей пароль pass4samvel , табличное пространство по умолчанию будет tbs_01 с квотой в 20 МБ, а временным табличным пространством будет tbs_01 .
4. Привилегии Grant объекта
После того, как вы создали свои объекты в схеме, вам необходимо предоставить привилегии, чтобы другие схемы/пользователи могли обращаться к вашим объектам базы данных (т.е. таблицам).
Параметры и аргументы
user_name
Имя учетной записи базы данных, которую вы хотите создать.
PROFILE profile_name
Необязательный. Это имя профиля, который вы хотите назначить для учетной записи пользователя, чтобы ограничить объем ресурсов базы данных, присвоенных учетной записи пользователя. Если опустить этот параметр, профиль по умолчанию присваивается пользователю.
PASSWORD EXPIRE
Необязательный. Если этот параметр установлен, то пароль должен быть сброшен до того, как пользователь может войти в базу данных Oracle.
ACCOUNT LOCK
Необязательный. Он отключает доступ к учетной записи пользователя.
ACCOUNT UNLOCK
Необязательный. Включает доступ к учетной записи пользователя.
Читайте также: