oracle lob что это
Русские Блоги
Oracle-DBMS_LOB функция и использование
Oracle-DBMS_LOB функция и использование
GETLENGTH
Функция, возвращающая длину указанных LOB-данных.
OPEN
READ
Процесс чтения данных указанной длины из данных LOB в буфер (в переменной)
пример:
WRITE
Процесс записи указанного количества данных в LOB.
пример:
APPEND
Процесс добавления указанных LOB-данных к указанным LOB-данным.
пример:
WRITEAPPEND
Записать данные буфера в конец LOB
TRIM
Процесс усечения части данных указанной длины с первой позиции в данных LOB.
пример:
CLOSE
Закройте открытый LOB
SUBSTR
Функция для извлечения подстрок из данных LOB.
пример:
INSTR
Функция для поиска позиции подстроки из данных LOB.
пример:
COMPARE
ERASE
Процесс удаления части данных в указанном месте в данных LOB.
пример:
COPY
Скопируйте исходный LOB в целевой LOB из указанной позиции
пример:
CREATETEMPORARY
Создание временного LOB во временном табличном пространстве пользователя
ISTEMPORARY
Определите, является ли локатор временным LOB
FILEEXISTS
Определите, существует ли файл ОС, соответствующий FILE_LOC. 1: существует; 0: не существует
FILEGETNAME
Получить псевдоним каталога и имя файла, соответствующие локатору BFILE
FILEISOPEN
Определите, открыт ли файл ОС, соответствующий BFILE.
FREETEMPORARY
Освободите временный LOB во временном табличном пространстве по умолчанию
FILEOPEN
Откройте файл
LOADBLOBFROMFILE
Загрузите данные BFILE в BLOB и получите последнюю позицию смещения после загрузки
пример:
FILECLOSE
Закройте файл ОС, на который указывает открытый локатор BFILE.
FILECLOSEALL
Закройте все файлы BFILE, открытые в текущем сеансе.
Oracle lob что это
Working with LOBs for application development requires that you understand LOB semantics and various techniques used with LOBs.
Most of the discussions regarding persistent LOBs assume that you are dealing with existing LOBs in tables. The task of creating tables with LOB columns is typically performed by your database administrator.
Using Oracle LOB Storage for creating LOBs using the SecureFiles paradigm
LOB Storage with Applications for storage parameters used in creating LOBs
2.1 LOB Column States
The techniques you use when accessing a cell in a LOB column differ depending on the state of the given cell.
A cell in a LOB Column can be in one of the following states:
The table cell is created, but the cell holds no locator or value.
A LOB instance with a locator exists in the cell, but it has no value. The length of the LOB is zero.
A LOB instance with a locator and a value exists in the cell.
2.2 Locking a Row Containing a LOB
You can lock a row containing a LOB to prevent other database users from writing to the LOB during a transaction.
To lock the row, specify the FOR UPDATE clause when you select the row. While the row is locked, other users cannot lock or update the LOB until you end your transaction.
2.3 LOB Open and Close Operations
The LOB APIs include operations that enable you to explicitly open and close a LOB instance.
Open the LOB in read-only mode
This ensures that the LOB (both the LOB locator and LOB value) cannot be changed in your session until you explicitly close the LOB. For example, you can open the LOB to ensure that the LOB is not changed by some other part of your program while you are using the LOB in a critical operation. After you perform the operation, you can then close the LOB.
Opening a LOB in read/write mode defers any index maintenance on the LOB column until you close the LOB. Opening a LOB in read/write mode is only useful if there is an extensible index on the LOB column, and you do not want the database to perform index maintenance every time you write to the LOB. This technique can increase the performance of your application if you are doing several write operations on the LOB while it is open.
If you open a LOB, then you must close the LOB at some point later in your session. This is the only requirement for an open LOB. While a LOB instance is open, you can perform as many operations as you want on the LOB—provided the operations are allowed in the given mode.
2.4 LOB Locator and LOB Value
You can use two different techniques to access and modify LOB values.
81 DBMS_LOB
This chapter contains the following topics:
Using DBMS_LOB
Overview
Security Model
Any DBMS_LOB subprogram called from an anonymous PL/SQL block is executed using the privileges of the current user. Any DBMS_LOB subprogram called from a stored procedure is executed using the privileges of the owner of the stored procedure.
When creating the procedure, users can set the AUTHID to indicate whether they want definer’s rights or invoker’s rights. For example:
For more information on AUTHID and privileges, see Oracle Database PL/SQL Language Reference
For information about the security model pertaining to temporary LOB s, see Operational Notes.
Constants
The DBMS_LOB package uses the constants shown in following tables:
Create the TEMP LOB with call duration
Open the specified BFILE read-only
Open the specified LOB read-only
Open the specified LOB read-write
Maximum size of a LOB in bytes
Create the TEMP LOB with session duration
Set/Get the SECUREFILE compress option value
Set/Get the SECUREFILE Deduplicate option value
Get the SECUREFILE encrypt option value
For SETOPTIONS Procedures, set compress off; for GETOPTIONS Functions, compress is off
For SETOPTIONS Procedures, set compress on; for GETOPTIONS Functions, compress is on
For SETOPTIONS Procedures, set deduplicate is off; for GETOPTIONS Functions, deduplicate is off
For SETOPTIONS Procedures, set deduplicate is on; for GETOPTIONS Functions, deduplicate is on
LOB has never been archived
LOB was archived, but as been read back in to the RDBMS
LOB is currently archived
Put the LOB data to the archive, but keep the data in the RDBMS as a cached version
Put the LOB data to the archive, and remove the data from the RDBMS.
Maximum number of bytes allowed in the content type string
Datatypes
The DBMS_LOB package uses the datatypes shown in Table 81-7.
Table 81-7 Datatypes Used by DBMS_LOB
Source or destination RAW buffer (used with BLOB ).
Source or destination character LOB (including NCLOB ).
Source or destination character buffer (used with CLOB and NCLOB ).
Large, binary object stored outside the database.
The DBMS_LOB package defines no special types.
An NCLOB is a CLOB for holding fixed-width and varying-width, multibyte national character sets.
The clause ANY_CS in the specification of DBMS_LOB subprograms for CLOB s enables the CLOB type to accept a CLOB or NCLOB locator variable as input.
Rules and Limits
General Rules and Limits
The following rules apply in the specification of subprograms in this package:
A subprogram raises an INVALID_ARGVAL exception if the following restrictions are not followed in specifying values for parameters (unless otherwise specified):
Only positive, absolute offsets from the beginning of LOB data are permitted: Negative offsets from the tail of the LOB are not permitted.
For example, if the CLOB consists of 2-byte characters, such as:
Then, the maximum amount value should not exceed:
PL/SQL language specifications stipulate an upper limit of 32767 bytes (not characters) for RAW and VARCHAR2 parameters used in DBMS_LOB subprograms. For example, if you declare a variable to be:
The %CHARSET clause indicates that the form of the parameter with %CHARSET must match the form of the ANY_CS parameter to which it refers.
If the value of amount plus the offset exceeds the maximum LOB size allowed by the database, then access exceptions are raised.
For consistent LOB updates, you must lock the row containing the destination LOB before making a call to any of the procedures (mutators) that modify LOB data.
Unless otherwise stated, the default value for an offset parameter is 1, which indicates the first byte in the BLOB or BFILE data, and the first character in the CLOB or NCLOB value. No default values are specified for the amount parameter — you must input the values explicitly.
Rules and Limits Specific to External Files (BFILEs)
DBMS_LOB does not support any concurrency control mechanism for BFILE operations.
In the event of several open files in the session whose closure has not been handled properly, you can use the FILECLOSEALL subprogram to close all files opened in the session and resume file operations from the beginning.
All files opened during a user session are implicitly closed at the end of the session. However, Oracle strongly recommends that you close the files after both normal and abnormal termination of operations on the BFILE.
In the event of abnormal program termination from a PL/SQL program, it is imperative that you provide an exception handler that ensures closure of all files opened in that PL/SQL program. This is necessary because after an exception occurs, only the exception handler has access to the BFILE variable in its most current state.
After the exception transfers program control outside the PL/SQL program block, all references to the open BFILEs are lost. The result is a larger open file count which may or may not exceed the SESSION_MAX_OPEN_FILES value.
For example, consider a READ operation past the end of the BFILE value, which generates a NO_DATA_FOUND exception:
After the exception has occurred, the BFILE locator variable file goes out of scope, and no further operations on the file can be done using that variable. Therefore, the solution is to use an exception handler:
In general, you should ensure that files opened in a PL/SQL block using DBMS_LOB are closed before normal or abnormal termination of the block.
Maximum LOB Size
Maximum Buffer Size
Operational Notes
All DBMS_LOB subprograms work based on LOB locators. For the successful completion of DBMS_LOB subprograms, you must provide an input locator that represents a LOB that already exists in the database tablespaces or external file system. See also Chapter 1 of Oracle Database SecureFiles and Large Objects Developer’s Guide.
To use LOBs in your database, you must first use SQL data definition language (DDL) to define the tables that contain LOB columns.
Internal LOBs
To populate your table with internal LOBs after LOB columns are defined in a table, you use the SQL data manipulation language (DML) to initialize or populate the locators in the LOB columns.
External LOBs
For an external LOB (BFILE) to be represented by a LOB locator, you must:
Ensure that a DIRECTORY object representing a valid, existing physical directory has been defined, and that physical files (the LOBs you plan to add) exist with read permission for the database. If your operating system uses case-sensitive path names, then be sure you specify the directory in the correct format.
Once you have completed these tasks, you can insert or update a row containing a LOB column using the specified LOB locator.
After the LOBs are defined and created, you can then SELECT from a LOB locator into a local PL/SQL LOB variable and use this variable as an input parameter to DBMS_LOB for access to the LOB value.
For details on the different ways to do this, you must refer to the section of the Oracle Database SecureFiles and Large Objects Developer’s Guide that describes «Accessing External LOBs (BFILEs).»
Temporary LOBs
The database supports the definition, creation, deletion, access, and update of temporary LOBs. Your temporary tablespace stores the temporary LOB data. Temporary LOBs are not permanently stored in the database. Their purpose is mainly to perform transformations on LOB data.
A temporary LOB is empty when it is created. By default, all temporary LOBs are deleted at the end of the session in which they were created. If a process dies unexpectedly or if the database crashes, then temporary LOBs are deleted, and the space for temporary LOBs is freed.
There is no support for consistent read (CR), undo, backup, parallel processing, or transaction management for temporary LOBs. Because CR and rollbacks are not supported for temporary LOBs, you must free the temporary LOB and start over again if you encounter an error.
Because temporary LOBs are not associated with any table schema, there are no meanings to the terms in-row and out-of-row temporary LOBs. Creation of a temporary LOB instance by a user causes the engine to create and return a locator to the LOB data. The PL/SQL DBMS_LOB package, PRO*C/C++, OCI, and other programmatic interfaces operate on temporary LOBs through these locators just as they do for permanent LOBs.
There is no support for client side temporary LOBs. All temporary LOBs reside in the server.
Temporary LOBs do not support the EMPTY_BLOB or EMPTY_CLOB functions that are supported for permanent LOBs. The EMPTY_BLOB function specifies the fact that the LOB is initialized, but not populated with any data.
A temporary LOB instance can only be destroyed by using OCI or the DBMS_LOB package by using the appropriate FREETEMPORARY or OCIDurationEnd statement.
A temporary LOB instance can be accessed and modified using appropriate OCI and DBMS_LOB statements, just as for regular permanent internal LOBs. To make a temporary LOB permanent, you must explicitly use the OCI or DBMS_LOB COPY command, and copy the temporary LOB into a permanent one.
Security is provided through the LOB locator. Only the user who created the temporary LOB is able to see it. Locators are not expected to be able to pass from one user’s session to another. Even if someone did pass a locator from one session to another, they would not access the temporary LOBs from the original session. Temporary LOB lookup is localized to each user’s own session. Someone using a locator from somewhere else is only able to access LOBs within his own session that have the same LOB ID. Users should not try to do this, but if they do, they are not able to affect anyone else’s data.
The following notes are specific to temporary LOBs:
Operations based on CLOBs do not verify if the character set IDs of the parameters ( CLOB parameters, VARCHAR2 buffers and patterns, and so on) match. It is the user’s responsibility to ensure this.
Data storage resources are controlled by the DBA by creating different temporary tablespaces. DBAs can define separate temporary tablespaces for different users, if necessary.
Oracle Lob Класс
Определение
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет двоичный тип данных больших объектов ( LOB ), хранящихся на сервере Oracle. Этот класс не наследуется.
Комментарии
OracleLobМожет быть одним из этих OracleType типов данных.
Тип данных OracleType | Описание |
---|---|
Blob | BLOB Тип данных Oracle, который содержит двоичные данные с максимальным размером 4 гигабайта (ГБ). Соответствует Array типа Byte. |
Clob | CLOB Тип данных Oracle, который содержит символьные данные, основанный на кодировке по умолчанию на сервере, с максимальным размером 4 ГБ. Соответствует String. |
NClob | NCLOB Тип данных Oracle, который содержит символьные данные на основе набора национальных символов на сервере с максимальным размером 4 ГБ. Соответствует String. |
После получения LOB значения Oracle из базы данных Oracle в OracleLob класс можно изменить LOB данные в открытой транзакции, и изменения будут непосредственно отражены в базе данных. Если значение Oracle извлекается LOB в Array тип Byte или String и обновляются эти массивы, изменения не отражаются в базе данных.
При использовании OracleLob класса для доступа к блоку LOB значения только этот блок передается клиенту из базы данных Oracle. При использовании GetChars метода для доступа к блоку LOB значения все содержимое значения передается клиенту из базы данных Oracle.
Чтобы получить OracleLob объект, вызовите GetOracleLob метод.
Можно создать, имеющий OracleLob значение null, в следующем формате:
Значение NULL LOB ведет себя так же, как нулевой байт LOB в, который Read завершается успешно и всегда возвращает нулевые байты.
В следующем примере показано, как открыть временную LOB :
Унаследованный WriteByte метод завершается ошибкой, если используется с символьными данными, и InvalidOperationException вызывается исключение. Вместо этого рекомендуется использовать метод Write.
Представляет пустой объект OracleLob.
Свойства
Получает значение, показывающее, могут ли быть выполнены операции прямого и обратного поиска.
Возвращает значение, которое показывает, может ли для данного потока истечь время ожидания.
Всегда возвращает логическое значение ИСТИНА, независимо от того, поддерживает ли LOB запись или нет.
Получает значение, определяющее минимальное количество байтов, которое необходимо извлечь с сервера или отправить на сервер при выполнении операции чтения или записи.
Получает OracleConnection, используемый данным экземпляром OracleLob.
Получает значение, определяющее, вызвало ли приложение метод BeginBatch().
Получает значение, определяющее, является ли OracleLob потоком Null.
Получает значение, возвращающее размер OracleLob.
Получает текущую позицию чтения в потоке OracleLob.
Возвращает или задает значение в миллисекундах, определяющее период времени, отведенного потоку на выполнение операции чтения.
Получает эквивалент общеязыковой среды выполнения потока для базового значения.
Возвращает или задает значение в миллисекундах, определяющее период времени, отведенного потоку на выполнение операции записи.
Методы
Предотвращает срабатывание серверных триггеров при выполнении нескольких операций чтения.
Предотвращает срабатывание серверных триггеров при выполнении нескольких операций чтения и записи в указанном режиме доступа.
Начинает операцию асинхронного чтения. (Рекомендуется использовать ReadAsync(Byte[], Int32, Int32).)
Начинает операцию асинхронной записи. (Рекомендуется использовать WriteAsync(Byte[], Int32, Int32).)
Создает новый объект OracleLob, который ссылается на тот же LOB Oracle, что и исходный объект OracleLob.
Закрывает текущий поток и освобождает все ресурсы, связанные с данным потоком.
Закрывает текущий поток и отключает все ресурсы (например, сокеты и файловые дескрипторы), связанные с текущим потоком. Вместо вызова данного метода, убедитесь в том, что поток надлежащим образом ликвидирован.
Копирует из данного объекта OracleLob в OracleLob, являющийся объектом назначения, с указанным объемом данных и смещением источника.
Копирует из данного объекта OracleLob в объект назначения — OracleLob.
Копирование из данного объекта OracleLob в объект назначения — OracleLob с указанным объемом данных.
Считывает байты из текущего потока и записывает их в другой поток.
Считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера.
Асинхронно считывает байты из текущего потока и записывает их в другой поток.
Асинхронно считывает байты из текущего потока и записывает их в другой поток, используя указанный токен отмены.
Асинхронно считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера.
Асинхронно считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера и токен отмены.
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом.
Освобождает ресурсы, используемые данным объектом.
Освобождает все ресурсы, занятые модулем Stream.
Освобождает неуправляемые ресурсы, используемые объектом Stream, а при необходимости освобождает также управляемые ресурсы.
Асинхронно освобождает неуправляемые ресурсы, используемые классом Stream.
Позволяет серверным триггерам возобновить работу после выполнения нескольких операций записи.
Ожидает завершения отложенного асинхронного чтения. (Рекомендуется использовать ReadAsync(Byte[], Int32, Int32).)
Заканчивает операцию асинхронной записи. (Рекомендуется использовать WriteAsync(Byte[], Int32, Int32).)
Определяет, равен ли указанный объект текущему объекту.
Удаляет все данные из этого OracleLob.
Удаляет заданный объем данных из этого OracleLob.
В настоящее время не поддерживается.
Асинхронно очищает все буферы для этого потока и вызывает запись всех буферизованных данных в базовое устройство.
Асинхронно очищает все буферы данного потока, вызывает запись буферизованных данных в базовое устройство и отслеживает запросы отмены.
Служит хэш-функцией по умолчанию.
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра.
Возвращает объект Type для текущего экземпляра.
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.
Создает неполную копию текущего объекта Object.
Создает неполную копию текущего объекта MarshalByRefObject.
Обеспечивает поддержку для Contract.
Считывает последовательность байтов из текущего потока OracleLob и перемещает позицию внутри потока на число считанных байтов.
При переопределении в производном классе считывает последовательность байтов из текущего потока и перемещает позицию в потоке на число считанных байтов.
Асинхронно считывает последовательность байтов из текущего потока и перемещает позицию внутри потока на число считанных байтов.
Асинхронно считывает последовательность байтов из текущего потока, перемещает позицию в потоке на число считанных байтов и отслеживает запросы отмены.
Асинхронно считывает последовательность байтов из текущего потока, перемещает позицию в потоке на число считанных байтов и отслеживает запросы отмены.
Задает позицию в текущем потоке OracleLob.
Задает длину потока OracleLob меньше текущей длины.
Возвращает строку, представляющую текущий объект.
Записывает последовательность байтов в текущий поток OracleLob и перемещает текущую позицию внутри потока на число записанных байтов.
При переопределении в производном классе записывает последовательность байтов в текущий поток и перемещает текущую позицию в нем вперед на число записанных байтов.
Асинхронно записывает последовательность байтов в текущий поток и перемещает текущую позицию внутри потока на число записанных байтов.
Асинхронно записывает последовательность байтов в текущий поток, перемещает текущую позицию внутри потока на число записанных байтов и отслеживает запросы отмены.
Асинхронно записывает последовательность байтов в текущий поток, перемещает текущую позицию внутри потока на число записанных байтов и отслеживает запросы отмены.
Записывает байт в текущее положение в потоке OracleLob, при этом позиция в потоке перемещается вперед на один байт.
Записывает байт в текущее положение в потоке и перемещает позицию в потоке вперед на один байт.
Явные реализации интерфейса
Освобождает все ресурсы, занятые модулем Stream.
11 LOB Storage
This chapter describes issues specific to tables that contain LOB columns, with both the SECUREFILE and BASICFILE parameters. If a feature applies to only one of the two kinds of LOB, it is so stated.
This chapter contains these topics:
Creating Tables That Contain LOBs
When creating tables that contain LOBs, use the guidelines described in the following sections:
Initializing Persistent LOBs to NULL or Empty
You can set a persistent LOB — that is, a LOB column in a table, or a LOB attribute in an object type that you defined— to be NULL or empty:
Setting a Persistent LOB to NULL : A LOB set to NULL has no locator. A NULL value is stored in the row in the table, not a locator. This is the same process as for all other data types.
Setting a Persistent LOB to Empty : By contrast, an empty LOB stored in a table is a LOB of zero length that has a locator. So, if you SELECT from an empty LOB column or attribute, then you get back a locator which you can use to populate the LOB with data using supported programmatic environments, such as OCI or PL/SQL(DBMS_LOB ). See Chapter 13, «Overview of Supplied LOB APIs» for more information on supported environments.
Details for these options are given in the following discussions.
Setting a Persistent LOB to NULL
You may want to set a persistent LOB value to NULL upon inserting the row in cases where you do not have the LOB data at the time of the INSERT or if you want to use a SELECT statement, such as the following, to determine whether the LOB holds a NULL value:
Note that you cannot call OCI or DBMS_LOB functions on a NULL LOB, so you must then use an SQL UPDATE statement to reset the LOB column to a non- NULL (or empty) value.
Setting a Persistent LOB to Empty
As an alternative, you can use the RETURNING clause to obtain the LOB locator in one operation rather than calling a subsequent SELECT statement:
Initializing LOBs
You can initialize the LOBs in print_media by using the following INSERT statement:
Initializing Persistent LOB Columns and Attributes to a Value
You can initialize the LOB column or LOB attributes to a value that contains more than 4G bytes of data, the limit before release 10.2.
Initializing BFILEs to NULL or a File Name
A BFILE can be initialized to NULL or to a filename. To do so, you can use the BFILENAME() function.
Restriction on First Extent of a LOB Segment
The first extent of any segment requires at least 2 blocks (if FREELIST GROUPS was 0). That is, the initial extent size of the segment should be at least 2 blocks. LOBs segments are different because they need at least 3 blocks in the first extent. If you try to create a LOB segment in a permanent dictionary managed tablespace with initial = 2 blocks, then it still works because it is possible for segments in permanent dictionary-managed tablespaces to override the default storage setting of the tablespaces.
But if uniform locally managed tablespaces or dictionary managed tablespaces of the temporary type, or locally managed temporary tablespaces have an extent size of 2 blocks, then LOB segments cannot be created in these tablespaces. This is because in these tablespace types, extent sizes are fixed and the default storage setting of the tablespaces is not ignored.
Choosing a LOB Column Data Type
When selecting a data type, consider the following three topics:
LOBs Compared to LONG and LONG RAW Types
Table 11-1 lists the similarities and differences between LOBs, LONGs, and LONG RAW types.
Table 11-1 LOBs Vs. LONG RAW
LOB Data Type | LONG and LONG RAW Data Type | ||||||||
---|---|---|---|---|---|---|---|---|---|
BasicFiles LOB Update Pattern | BasicFiles LOB Read Pattern | PCTVERSION | ||||
---|---|---|---|---|---|---|
Cache Mode | Read | Write | |
---|---|---|---|
Data Size | CHUNK Size | Disk Space Used to Store the LOB | Space Utilization (Percent) |
---|---|---|---|