Webutil_file_transfer for bfile
Is there a way to have webutil download a bfile from the DB to the client?
Thanks,
Michelle
Doh, sorry. I posted too quickly. We just solved the problem for BLOBs, and I guess it gave me tunnel vision.
Maybe, if you don't get another answer, you could call a function you set up on the database which moves a BFILE into a global temporary table, then follows the instructions in that link? Then do the reverse if you also need to save the file back?
-=cf
Similar Messages
-
Is Directory Creation necessary for BFILE ?
I created a table with one column as bfile
while inserting the value in that column using directory
it works fine
but when i use direct path instaed of directory it gives value error.
for example: INSERT INTO ABC_BFILE_TEST (B)
VALUES ( BFILENAME('/export/home/devmgr','karan.txt'));
this inserts the row but with value error iam not able to open this document.
for example: INSERT INTO ABC_BFILE_TEST (B)
VALUES ( BFILENAME('DIRECTORY1','karan.txt'));
NOW IN THIS CASE directory1 is directory which i created in database
and represents the same path '/export/home/devmgr' and it works fine
Actually i have to pass the path and file name on runtime
so i dont want to create directory.
Could anybody help me on this.
Your reply is highly appreciable. :)But, as Michael says, I wouldn't recommend using UTL_FILE_DIR parameter.
It has a big security flaw in that whatever paths you set in it are available for read/write to ALL database users. Not generally a good idea to let every database user have access to all the specified folders on the file system.
And if you really do think that's the best way to do what you need, you should never (I repeat... NEVER!) set the utl_file_dir parameter to "*" as this will give every database user access to the whole filesystem of the database server, which could be disasterous. -
Help: Creating logical directory for BFILE data type.
I am trying to use BFILE datatype. For that I tried to create
directory using the command [ create directory 'test_dir' for
'physiacl_path' ] . It gives error ORA-22929, which says
'Invalid or missing directory name'.
I tried this on UNIX (Oracle 8) and NT (Oracle 8I) and same
problem comes.
Please send us any nearest solution to this problem.
Thanks
Pawan
nullPawan Kumar (guest) wrote:
: I am trying to use BFILE datatype. For that I tried to create
: directory using the command [ create directory 'test_dir' for
: 'physiacl_path' ] . It gives error ORA-22929, which says
: 'Invalid or missing directory name'.
: I tried this on UNIX (Oracle 8) and NT (Oracle 8I) and same
: problem comes.
: Please send us any nearest solution to this problem.
: Thanks
: Pawan
When I use this command [create directory 'test_dir' for
: 'physiacl_path'] I get an error ORA-00905.
Instead of 'for' use 'as' and this will work.
That is, use the command:
[ create directory 'test_dir' AS
: 'physiacl_path' ]
null -
I wonder why it could be useful for bfile datatype
may be i do know understand exactly,
i always wonder, why we need a bfile for storage?
we also can store the path/filename as a string in any char datatype, so as to get the feaures of bfile more easily, then why oracle make up a datatype as bfile.
what is its special advantages?
thanks for your tips
nullHi,
Following is a very brief explanation of the BFILE data type. See the Oracle8i documentation for more information. Oracle8i Application Developer's Guide - Large Objects (LOBs) can be found at: http://otn.oracle.com/docs/products/oracle8i/doc_library/817_doc/appdev.817/a76940/toc.htm
The BFILE data type is one of the Oracle data types used to access Large OBjects or LOBs. A BFILE is an external LOB type (that is to say, the data is stored externally to the database), while BLOBs and CLOBs are internal LOB types (that is to say, the data is stored internally in the database). All the LOB types share a common API, with the methods such as open and close, read and write (write support for internal LOBs only), and others such as methods to get the LOB length. The LOB interface is the only way to access LOB data from within the database, whether the data is stored internally, as BLOBs or CLOBs, or externally, as BFILEs. (Actually, it is possible to access files on the database server using Java Stored Procedures in the database, given the right access permissions. But that's a different story and doesn't have anything to do with LOBs as such.)
An application can choose whether to store a 'reference' to an external LOB as a BFILE, or as a database directory name plus the file name. If the reference is stored as a BFILE, then the application can access the LOB data directly. If the reference is stored as a database directory name plus file name, then, before accessing the LOB data, the application must first create a BFILE LOB locator using the BFILENAME SQL function.
To sum up:
1) The Oracle BFILE LOB data type is used to specify a LOB locator using which applications access the LOB data.
2) Do applications have to use the BFILE data type to reference external LOB data? No, an application can store the database directory name plus the file name, and create a BFILE data type only when the application needs to read the LOB data.
Hope that helps,
Simon
null -
I developed an application based on Oracle Database Express Edition which stores data about Word documents about scripts that generates the client to use this kind of a field BFILE.
Each file generated by the customer, has an average size of 50KB, generated an average of 20 files per day (Monday through Friday).
My question is: If the use BFILES consumes much storage space in the Oracle database XE?, I am concerned about this situation by limiting 4GB for storage of user data.
RobertoHi,
I don't know much about BLOB/CLOB, or BFILE, but I know that if you use BIFLE, you are not actually storing the unsctructured file itself, i.e, word doc , in the database, but only a pointer(comparing the file itself, in your case, 50kb, the pointer itself should be very tiny) indicating where it is at the local OS file system.
So, I think you can store a lot of file, much more than 4 GB, it should be Ok, because that files are within the filesystem of the OS, not the db itself.
As from the documentation- Concept:
BFILE Datatype
The BFILE datatype stores unstructured binary data in operating-system files outside the database. A BFILE column or attribute stores a file locator that points to an external file containing the data. BFILEs can store up to 8 terabytes of data.
BFILEs are read only; you cannot modify them. They support only random (not sequential) reads, and they do not participate in transactions. The underlying operating system must maintain the file integrity, security, and durability for BFILEs. The database administrator must ensure that the file exists and that Oracle processes have operating-system read permissions on the file.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/datatype.htm#sthref3873
Peter -
I know that within clause works for XML in clob, but I tried to save XML in bfile, after I create index, the WITHIN query always return 0 rows, does WITHIN work for bfile?
ThanksNote:121405.1
Subject:
How to load a XML file into a Database table
Type:
BULLETIN
Status:
REVIEWED
Content Type:
TEXT/PLAIN
Creation Date:
05-OCT-2000
Last Revision Date:
06-OCT-2000
Language:
USAENG
This article is being delivered in Draft form and may contain
errors. Please use the MetaLink "Feedback" button to advise
Oracle of any issues related to this article.
PURPOSE
This note is intended to explain the way to load a XML file into database table from PL/SQL.
SCOPE
It is intended for XML developers and technical analysts who want to integrate XML and Oracle.
Pre-requisites :
1. Oracle RDBMS version is 8.1.6 or higher.
2. Oracle JServer is installed.
3. XML-SQL (XSU) Utility is installed.
XML file ( example.xml ):
Note :
The <ROWSET> tag specifies the default tag name for the document.
The <ROW> tag specifies the default tag name for the ROW elements.
- - - - - - - - - - - - - - - - File begins here - - - - - - - - - - - - - - - -
<ROWSET>
<ROW>
<DOCID> 91739.1 </DOCID>
<SUBJECT> MTS: ORA-29855, DRG-50704, ORA-12154: on create index using Intermedia </SUBJECT>
<TYPE> PROBLEM </TYPE>
<CONTENT_TYPE> TEXT/PLAIN </CONTENT_TYPE>
<STATUS> PUBLISHED </STATUS>
<CREATION_DATE> 14-DEC-1999 </CREATION_DATE>
<LAST_REVISION_DATE> 05-JUN-2000 </LAST_REVISION_DATE>
<LANGUAGE> USAENG </LANGUAGE>
</ROW>
</ROWSET>
- - - - - - - - - - - - - - - - File ends here - - - - - - - - - - - - - - - -
Program Notes :
The following data structures are to be set up for the example to work :
Create directory object mapped to physical directory which contain the XML file.
Note Oracle user should have atleast read permission for the directory and the XML file.
CREATE DIRECTORY XML_DIR AS '/tmp';
Create a table containing a BFILE and insert a row for the XML file.
CREATE TABLE XML_TEMP (key NUMBER, f_lob BFILE);
INSERT INTO XML_TEMP VALUES (1,BFILENAME('XML_DIR','example.xml'));
Create table into which the XML document has to be loaded.
Note that the column names of the table should match the XML tags.
CREATE TABLE XML_DOC (
DOCID VARCHAR2(10),
SUBJECT VARCHAR2(100),
TYPE VARCHAR2(20),
CONTENT_TYPE VARCHAR2(20),
STATUS VARCHAR2(20),
CREATION_DATE VARCHAR2(15),
LAST_REVISION_DATE VARCHAR2(15),
LANGUAGE VARCHAR2(10)
Program :
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - - - - - -
CREATE OR REPLACE PROCEDURE loadxml AS
fil BFILE;
buffer RAW(32767);
len INTEGER;
insrow INTEGER;
BEGIN
SELECT f_lob INTO fil FROM xml_temp WHERE key = 1;
DBMS_LOB.FILEOPEN(fil,DBMS_LOB.FILE_READONLY);
len := DBMS_LOB.GETLENGTH(fil);
DBMS_LOB.READ(fil,len,1,buffer);
xmlgen.resetOptions;
insrow := xmlgen.insertXML('xml_doc',UTL_RAW.CAST_TO_VARCHAR2(buffer));
DBMS_OUTPUT.PUT_LINE(insrow);
IF DBMS_LOB.FILEISOPEN(fil) = 1 THEN
DBMS_LOB.FILECLOSE(fil);
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('In Exception');
DBMS_OUTPUT.PUT_LINE(SQLERRM(SQLCODE));
IF DBMS_LOB.FILEISOPEN(fil) = 1 THEN
DBMS_LOB.FILECLOSE(fil);
END IF;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - - - - - -
Sample Output :
SQL>set serveroutput on
SQL>exec loadxml;
SQL> column subject format a20 truncated
SQL> select * from xml_doc;
SQL>
DOCID SUBJECT TYPE
CONTENT_TYPE STATUS CREATION_DATE LAST_REVISION_D LANGUAGE
91739.1 MTS: ORA-29855, DRG PROBLEM TEXT/PLAIN
PUBLISHED 14-DEC-1999 15-JUN-2000 USAENG
R eferences :
1. Oracle8i Supplied PL/SQL Packages Reference
2. Oracle8i Application Developer's Guide - Large Objects (LOBs)
3. PL/SQL User's Guide and Reference
4. XSU's PL/SQL API -- XMLGEN -
Hi, anyone used BLOB or BFILE before?
Currently I am thinking of using BLOB or BFILE to store documents (.doc, .pdf, .ppt, .rft, .csv). Can decide yet on which to use. Anyone got any recommendation on which to use?
1. Any performace issue when using blob after i had stored it in a different tablespace?
2. Will it take much longer time for export if to use blob.
3. As for BFILE will it get corrupted if the physical files is delete or been moved to some other location?
Thanks you in advance, you comments/advice is greatly appreciated..
Regards,
lbinsoon1. If the blob is in a different tablespace from the row it resides in, that is not a performance impact.
2. Yes. And how much depends on how much blob data you have. This is because BFILE data is not exported, only the pointers are. So, if you have blob data, it IS exported, making for longer running exports.
3. Yes. Well, not corrupted, but, of course, you won't be able to access the file. You must update it to point to the new name or location, which can be done with a simple update stmt thus:
update bf set b = bfilename('d:\tmp','some_binary_file.dat')
assuming column b is of type BFILE.
Tom Best -
Hi All,
Can Anyone please tell how to compare clob type in select query with where condition ?
Ex: field: Desc_ short(Clob )
field ean_code(number,pk)
And i want to see those ean_code list matching to particullar clob pattern matching in the record in any where in the record.
Please help.
Thanks and regards,
DK.COMPARE function
This function compares two entire LOBs or parts of two LOBs. You can only compare LOBs of the same datatype (LOBs of BLOB type with other BLOBs, and CLOBs with CLOBs, and BFILEs with BFILEs). For BFILEs, the file must be already opened using a successful FILEOPEN operation for this operation to succeed.
COMPARE returns zero if the data exactly matches over the range specified by the offset and amount parameters. Otherwise, a non-zero INTEGER is returned.
For fixed-width n-byte CLOBs, if the input amount for COMPARE is specified to be greater than (4294967295/n), then COMPARE matches characters in a range of size (4294967295/n), or Max(length(clob1), length(clob2)), whichever is lesser.
Syntax
DBMS_LOB.COMPARE (
lob_1 IN BLOB,
lob_2 IN BLOB,
amount IN INTEGER := 4294967295,
offset_1 IN INTEGER := 1,
offset_2 IN INTEGER := 1)
RETURN INTEGER;
DBMS_LOB.COMPARE (
lob_1 IN CLOB CHARACTER SET ANY_CS,
lob_2 IN CLOB CHARACTER SET lob_1%CHARSET,
amount IN INTEGER := 4294967295,
offset_1 IN INTEGER := 1,
offset_2 IN INTEGER := 1)
RETURN INTEGER;
DBMS_LOB.COMPARE (
lob_1 IN BFILE,
lob_2 IN BFILE,
amount IN INTEGER,
offset_1 IN INTEGER := 1,
offset_2 IN INTEGER := 1)
RETURN INTEGER;
Pragmas
pragma restrict_references(COMPARE, WNDS, WNPS, RNDS, RNPS);
Parameters
Table 17-7 COMPARE Function Parameters
Parameter Description
lob_1 LOB locator of first target for comparison.
lob_2 LOB locator of second target for comparison.
amount Number of bytes (for BLOBs) or characters (for CLOBs) to compare.
offset_1 Offset in bytes or characters on the first LOB (origin: 1) for the comparison.
offset_2 Offset in bytes or characters on the first LOB (origin: 1) for the comparison.
Returns
INTEGER: Zero if the comparison succeeds, non-zero if not.
NULL, if
amount < 1
amount > LOBMAXSIZE
offset_1 or offset_2 < 1
offset_1 or offset_2 > LOBMAXSIZE
Exceptions
Table 17-8 COMPARE Function Exceptions for BFILE operations
Exception Description
UNOPENED_FILE
File was not opened using the input locator.
NOEXIST_DIRECTORY
Directory does not exist.
NOPRIV_DIRECTORY
You do not have privileges for the directory.
INVALID_DIRECTORY
Directory has been invalidated after the file was opened.
INVALID_OPERATION
File does not exist, or you do not have access privileges on the file.
http://www.java2s.com/Code/Oracle/System-Packages/Usedbmslobcomparetocompare.htm -
hi,
could you pls help me that what is the all process for bfile into blob and then how to see image in apexHello user,
You can create a function that returns a blob based on your bfile. Apex has default functionality dealing with blob's (http://www.oracle.com/technology/obe/apex/apex31nf/apex31blob.htm)
Use this article, but instead of the insert, return a blob in a function:
http://www.dba-oracle.com/t_store_insert_pdf_file_oracle_table_blob.htm
When you select your bfile, make sure you wrap the function around it, so that Apex will select a blob instead of a bfile.
I haven't tested this, but it sounds feasible. Looking forward hearing the results
Greetings,
Rutger
http://rutgerderuiter.blogspot.com/
===============================================================================
You can reward this reply by marking it as either Helpful or Correct ;-) -
Using BFILEs with IFS (backup of large IFS DB)
Greetings:
I am investigating IFS for a customer. The customer is concerned about backing up what could become a very large Oracle database if versioned documents are stored in the DB.
Is it possible to have IFS store it's documents in BFILEs (OS data files)? My customer thinks this would be easier to backup. My initial run through the documentation leads me think it is not possible, at least, with an out of the box implementation.
I see a glimmer of hope by extending the document classes and specifying BFILEs somehow. Has anyone done this?
TIA
...jlg (jim)Please ignore this thread - I was too fast in posting.
The answer to this query can be found by searching this forum for "BFILE".
Please excuse the unncessarry traffic.
...jlg -
In general what's faster? File size is around 50k each.
10g, Linux x86.Well the speed here depends very much on the underlying IO system.
BFILE doesn't get stored in the database. It's stored outside the DB on the file system of the operating system while BLOB is fully stored in the database but also here it depends what are you using (ASM, OS file system, ...)
In general I would suggest that you go for BLOB because of following key benefits:
* Stored inside the database
* Read/Writeable
* Can be cached
* Participate fully in transactions
* 11g has enhanced LOB (for upgrades somewhere in the future)
This is was the concept guide says about:
BFILE Datatype
The BFILE datatype stores unstructured binary data in operating-system files outside the database. A BFILE column or attribute stores a file locator that points to an external file containing the data. BFILEs can store up to 8 terabytes of data.
BFILEs are read only; you cannot modify them. They support only random (not sequential) reads, and they do not participate in transactions. The underlying operating system must maintain the file integrity, security, and durability for BFILEs. The database administrator must ensure that the file exists and that Oracle processes have operating-system read permissions on the file.
BLOB Datatype
The BLOB datatype stores unstructured binary data in the database. BLOBs can store up to 8 terabytes of binary data.
BLOBs participate fully in transactions. Changes made to a BLOB value by the DBMS_LOB package, PL/SQL, or the OCI can be committed or rolled back. However, BLOB locators cannot span transactions or sessions. -
Uploaded Files stored in Oracle 10G database or in Unix File system
Hey All,
I am trying to understand best practices on storing uploaded files. Should you store within the database itself (this is the current method we are using by leveraging BLOB storage) or use a BFILE locator to use the files system storage (we have our DB's on UNIX) . . .or is there another method I should be entertaining? I have read arguments on both sides of this question. I wanted to see what answers forum readers could provide!! I understand there are quite a few factors but the situation I am in is as follows:
1) Storing text and pdf documents.
2) File sizes range from a few Kb to up to 15MB in size
3) uploaded files can be deleted and updated / replaced quite frequently
Right now we have an Oracle stored procedure that is uploading the files binary data into a BLOB column on our table. We have no real "performance" problems with this method but are entertaining the idea of using the UNIX file system for storage instead of the database.
Thanks for the insight!!
Anthony RoederAnthony,
First word you must learn here in this forum is RESPECT.
If you require any further explanation, just say so.
BLOB compared with BFILE
Security:
BFILEs are inherently insecure, as insecure as your operating system (OS).
Features:
BFILEs are not writable from typical database APIs whereas BLOBs are.
One of the most important features is that BLOBs can participate in transactions and are recoverable. Not so for BFILEs.
Performance:
Roughly the same.
Upping the size of your buffer cache can make a BIG improvement in BLOB performance.
BLOBs can be configured to exist in Oracle's cache which should make repeated/multiple reads faster.
Piece wise/non-sequential access of a BLOB is known to be faster than a that of a BFILE.
Manageability:
Only the BFILE locator is stored in an Oracle BACKUP. One needs to do a separate backup to save the OS file that the BFILE locator points to. The BLOB data is backed up along with the rest of the database data.
Storage:
The amount of table space required to store file data in a BLOB will be larger than that of the file itself due to LOB index which is the reason for better BLOB performance for piece wise random access of the BLOB value. -
How to fetch images stored in database to reports
i have stored images in bfile type.i need to access the image.pls do inform me urgently.
Hi,
Follow the steps to access images using Reports.
1. create the sql query in datamodel editor.
2. Open property inspector for Bfile column
3. Set file format property to Image.
4. Goto Report's layout editor
5. Create field and required frames, set field's source to BFILE column name.
6. Now run the report
Thanks,
Oracle Reports Team. -
PRO*C에서 EMBEDDED SQL STATEMENTS를 사용해서 LOB DATATYPES에 접근하는 예제
제품 : PRECOMPILERS
작성날짜 : 2001-07-12
PRO*C에서 EMBEDDED SQL STATEMENTS를 사용해서 LOB DATATYPES에 접근하는 예제
==========================================================================
Pro*C에서 LOB를 사용하는 방법에는 다음 3가지가 있습니다.
(1) PL/SQL blocks에서 DBMS_LOB package를 이용하는 방법
(2) OCI function을 이용하는 방법
(3) Embedded SQL statements을 이용하는 방법
다음은 (3)번째 방법에 대한 pro*c에서 지원하는 명령어들입니다.
o APPEND: Appends lob value at the end of another LOB.
EXEC SQL LOB APPEND :src TO :dst;
o ASSIGN: Assigns LOB or BFILE locator to another.
EXEC SQL LOB ASSIGN :src TO :dst;
o CLOSE: Close LOB or BFILE.
EXEC SQL LOB CLOSE :src;
o COPY: Copy all or part of LOB value into another LOB.
EXEC SQL LOB COPY :amt FROM :src [AT :src_offset] TO :dst [AT dst_offset];
o CREATE TEMPORARY: Creates a temporary LOB.
EXEC SQL LOB CREATE TEMPORARY :src;
o ERASE: Erase the given amount of LOB data starting from a given offset.
EXEC SQL LOB ERASE :amt FROM :src [AT :src_offset];
o FILE CLOSE ALL: Closes all the BFILES open in the current session.
EXEC SQL LOB FILE CLOSE ALL;
o FILE SET: Set DIRECTORY alias and FILENAME in a BFILE locator.
EXEC SQL LOB FILE SET :file DIRECTORY = :alias, FILENAME = :filename;
o FREE TEMPORARY: Free the temporary space for the LOB locator.
EXEC SQL LOB FREE TEMPORARY :src
o LOAD FROM FILE: Copy all or part of BFIL into an internal LOB.
EXEC SQL LOB LOAD :amt FROM FILE :file [AT :src_offset]
INTO :dst [AT :dst_offset];
o OPEN: Open a LOB or BFILE for read or read/write.
EXEC SQL LOB OPEN :src [ READ ONLY | READ WRITE ];
o READ: Reads all or part of LOB or BFILE into a buffer.
EXEC SQL LOB READ :amt FROM :src [AT :src_offset]
INTO :buffer [WITH LENGTH :buffer];
o TRIM: Truncates the LOB vlaue.
EXEC SQL LOB TRIM :src to :newlen;
o WRITE: Writes contents of the buffer to a LOB.
EXEC SQL LOB WRITE [APPEND] [FIRST | NEXT | LAST | ONE ]
:amt FROM :buffer [WITH LENGTH :buflen] INTO :dst [AT :dst_offset];
o DESCRIBE: Retrieves the attributes from a LOB.
EXEC SQL LOB DESCRIBE :src GET attribute1 [{, attributeN}]
INTO :hv1 [[INDICATOR] :hv_ind1] [{, :hvN [[INDICATOR] :hv_indN] }];
Attributes can be any of the following:
CHUNKSIZE: chunk size used to store the LOB value
DIRECTORY: name of the DIRECTORY alias for BFILE
FILEEXISTS: whether BFILE exists or not
FILENAME: BFILE name
ISOPEN: whether BFILE with this locate is OPEN or not
ISTEMPORARY: whether specified LOB is temporary or not
LENGTH: Length of BLOBs and BFILE in bytes, CLOBs and NCLOBs
in characters.
다음은 LOB를 사용하는 sample을 실행하는 방법입니다.
1. 먼저 scott user에서 다음을 실행합니다. (create directory를 할 수 있는 권한이
있어야 하며, directory는 사용하시는 환경에 맞도록 수정해 주십시요.)
drop table lob_table;
create table lob_table (key number, a_blob BLOB, a_clob CLOB);
drop table lobdemo;
create table lobdemo (key number, a_blob BLOB, a_bfile BFILE);
drop directory dir_alias;
create directory dir_alias as '/users/app/oracle/product/8.1.7/precomp/demo/proc';
insert into lob_table values(1, utl_raw.cast_to_raw('1111111111'), 'aaaaaaaa');
commit;
2. 다음 코드는 out.gif 파일을 위에서 지정한 directory에 만들고 lob_table의
내용에 들어있는 BLOB의 내용을 저장하는 sample입니다.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sqlda.h>
#include <sqlcpr.h>
/* Define constants for VARCHAR lengths. */
#define UNAME_LEN 20
#define PWD_LEN 40
/* Declare variables. No declare section is
needed if MODE=ORACLE. */
VARCHAR username[UNAME_LEN]; /* VARCHAR is an Oracle-supplied struct */
varchar password[PWD_LEN]; /* varchar can be in lower case also. */
/* The following 3 lines avoid inclusion of oci.h during precompilation
oci.h is needed only during compilation to resolve calls generated by
the precompiler
#ifndef ORA_PROC
#include <oci.h>
#endif
#include <sqlca.h>
OCIBlobLocator *blob;
OCIClobLocator *clob;
FILE *fp;
unsigned int amt, offset = 1;
#define MAXBUFLEN 5000
unsigned char buffer[MAXBUFLEN];
EXEC SQL VAR buffer IS RAW(MAXBUFLEN);
/* Declare error handling function. */
void sql_error(msg)
char *msg;
char err_msg[128];
size_t buf_len, msg_len;
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\n%s\n", msg);
buf_len = sizeof (err_msg);
sqlglm(err_msg, &buf_len, &msg_len);
printf("%.*s\n", msg_len, err_msg);
EXEC SQL ROLLBACK RELEASE;
exit(EXIT_FAILURE);
void main()
/* Connect to ORACLE--
* Copy the username into the VARCHAR.
strncpy((char *) username.arr, "SCOTT", UNAME_LEN);
/* Set the length component of the VARCHAR. */
username.len =
(unsigned short) strlen((char *) username.arr);
/* Copy the password. */
strncpy((char *) password.arr, "TIGER", PWD_LEN);
password.len =
(unsigned short) strlen((char *) password.arr);
/* Register sql_error() as the error handler. */
EXEC SQL WHENEVER SQLERROR DO sql_error("ORACLE error--\n");
/* Connect to ORACLE. Program will call sql_error()
* if an error occurs when connecting to the default database.
EXEC SQL CONNECT :username IDENTIFIED BY :password;
printf("\nConnected to ORACLE as user: %s\n", username.arr);
/* Allocate the LOB host variables and select the BLOB value */
EXEC SQL ALLOCATE :blob;
EXEC SQL ALLOCATE :clob;
EXEC SQL SELECT a_blob INTO :blob FROM lob_table WHERE key=1;
/* Open external file to which BLOB value should be written */
fp = fopen("out.gif", "w");
EXEC SQL WHENEVER NOT FOUND GOTO end_of_lob;
amt = 5000;
EXEC SQL LOB READ :amt FROM :blob AT :offset INTO :buffer;
fwrite(buffer, MAXBUFLEN, 1, fp);
EXEC SQL WHENEVER NOT FOUND DO break;
/* Use polling method to continue reading the next pieces */
while (TRUE)
EXEC SQL LOB READ :amt FROM :blob INTO :buffer;
fwrite(buffer, MAXBUFLEN, 1, fp);
end_of_lob:
fwrite(buffer, amt, 1, fp);
printf("\nG'day.\n\n\n");
/* Disconnect from ORACLE. */
EXEC SQL ROLLBACK WORK RELEASE;
exit(EXIT_SUCCESS);
3. 다음 코드는 위에서 만든 out.gif file을 lobdemo에 저장하는 sample입니다.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sqlda.h>
#include <sqlcpr.h>
/* Define constants for VARCHAR lengths. */
#define UNAME_LEN 20
#define PWD_LEN 40
/* Declare variables. No declare section is
needed if MODE=ORACLE. */
VARCHAR username[UNAME_LEN]; /* VARCHAR is an Oracle-supplied struct */
varchar password[PWD_LEN]; /* varchar can be in lower case also. */
/* The following 3 lines avoid inclusion of oci.h during precompilation
oci.h is needed only during compilation to resolve call generated by
the precompiler
#ifndef ORA_PROC
#include <oci.h>
#endif
#include <sqlca.h>
OCIBlobLocator *blob;
OCIBFileLocator *bfile;
char *alias = "DIR_ALIAS";
char *filename = "out.gif";
unsigned int amt = 50;
unsigned int filelen;
/* Declare error handling function. */
void sql_error(msg)
char *msg;
char err_msg[128];
size_t buf_len, msg_len;
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\n%s\n", msg);
buf_len = sizeof (err_msg);
sqlglm(err_msg, &buf_len, &msg_len);
printf("%.*s\n", msg_len, err_msg);
EXEC SQL ROLLBACK RELEASE;
exit(EXIT_FAILURE);
void main()
/* Connect to ORACLE--
* Copy the username into the VARCHAR.
strncpy((char *) username.arr, "SCOTT", UNAME_LEN);
/* Set the length component of the VARCHAR. */
username.len =
(unsigned short) strlen((char *) username.arr);
/* Copy the password. */
strncpy((char *) password.arr, "TIGER", PWD_LEN);
password.len =
(unsigned short) strlen((char *) password.arr);
/* Register sql_error() as the error handler. */
EXEC SQL WHENEVER SQLERROR DO sql_error("ORACLE error--\n");
/* Connect to ORACLE. Program will call sql_error()
* if an error occurs when connecting to the default database.
EXEC SQL CONNECT :username IDENTIFIED BY :password;
printf("\nConnected to ORACLE as user: %s\n", username.arr);
/* Allocate the LOB locator */
EXEC SQL ALLOCATE :blob;
EXEC SQL ALLOCATE :bfile;
/* Initialize the DIRECTORY alias of the BFILE and FILENAME */
EXEC SQL LOB FILE SET :bfile
DIRECTORY = :alias, FILENAME = :filename;
EXEC SQL INSERT INTO lobdemo values (1, EMPTY_BLOB(), :bfile);
EXEC SQL SELECT a_blob, a_bfile INTO :blob, :bfile FROM lobdemo
WHERE key = 1;
EXEC SQL LOB OPEN :bfile;
/* Get the BFILE length */
EXEC SQL LOB DESCRIBE :bfile
GET LENGTH INTO :filelen;
printf("File length is: %d\n", filelen);
amt = filelen;
/* Read BFILE and write to BLOB */
EXEC SQL LOB LOAD :amt FROM FILE :bfile INTO :blob;
EXEC SQL LOB CLOSE :bfile;
printf("\nG'day.\n\n\n");
/* Disconnect from ORACLE. */
EXEC SQL COMMIT WORK RELEASE;
exit(EXIT_SUCCESS);
4. 다음은 실행한 결과 입니다.
첫번째 sample :
Connected to ORACLE as user: SCOTT
G'day.
두번째 sample :
Connected to ORACLE as user: SCOTT
File length is: 10
G'day. -
Oci_bind_by_name
Hi to all,
Can anyone explain how to use of oci_bind_by_name in more detail?
for example oci_bind_by_name(":oracle_parameter",$php_var, $maxlength [, int $type])
how do you specify the maxlength? what criteria to consider
what can you specify in $type? how do you use the $type ( actually i m more confused on this part)
what is the advancetage of using the oci_bind_by_name and how do you use these function
in my case oracle statement of mine is
$stmt = "select column1, column2 from (select column1, column2, row_num rnum from (select column1, column2 from table1) where row_num < :lastrow) where rnum> :firstrow";
$connection= oci_connect('hr', 'hr', 'orcl');
$q =oci_parse($connection, $query);
oci_bind_by_name ($q, ":firstrow" , 1); //is this possible?? because the it is bind to a number
oci_bind_by_name ($q, ":lastrow" , 1000); //??
oci_execute($q);
$q will be the array of your table blah blah.........
if you intend have the same page over and over again but just having row number change how would you use the oci_bind_by_name? do your php_page call the oci_connect again and do the binding for the page like the code above? how do you guys do to save some oracle resources...
by the way, i have also notice that if you perform a "order by" in the oracle query it does take some time...how to reduce this time..any recommendation?
thanks...
Message was edited by:
Jo EeHi,
Best source of info is PHP Manual: http://www.php.net/function.oci_bind_by_name
1. how do you specify the maxlength? what criteria to consider
"Sets the maximum length for the bind. If you set it to -1, this function will use the current length of variable to set the maximum length."
For input parameters you can use -1 (it's easy but can cause problems with scalability, as different values causes to create new child cursor in SGA. It's better to estimate what is your max and set it)
For output variables you have to set buffer length - what is the max length that can be returned from DB.
2.what can you specify in $type?
It can be one of:
#SQLT_FILE - for BFILEs;
#SQLT_CFILE - for CFILEs;
#SQLT_CLOB - for CLOBs;
#SQLT_BLOB - for BLOBs;
#SQLT_RDD - for ROWIDs;
#SQLT_NTY - for named datatypes;
#SQLT_INT - for integers;
#SQLT_CHR - for VARCHARs;
#SQLT_BIN - for RAW columns;
#SQLT_LNG - for LONG columns;
#SQLT_LBI - for LONG RAW columns;
#SQLT_RSET - for Ref cursosr
Default is SQLT_CHR. You should set proper type, otherwise you will have implicit type conversion.
In your case try:
oci_bind_by_name ($q, ":firstrow" , 1, 10, SQLT_INT);
oci_bind_by_name ($q, ":lastrow" , 1000, 10, SQLT_INT);
3. if you intend have the same page over and over again but just having row number change how would you use the oci_bind_by_name? do your php_page call the oci_connect again and do the binding for the page like the code above?
Well, every page is new request. And for every page you have to obtain persistent connection (oci_pconnect) or create new connection (oci_connect). I recommend using persistent connections. (BTW. in Oracle 11g it is even improved by Database Resident Connection Pooling).
If you use persistent connections and cursors with bind variables, then cursors are kept parsed in session, and when you execute oci_parse existing execution plan is reused.
Regards,
Paweł
Maybe you are looking for
-
I can no longer manually drag music or podcasts on to my iphone 4. Help?!
i have a PC. First of all, the other day i opened itunes to discover that all of my music had disappeared from it. I then had to get it to find all the music and my computer and import it. I then discovered I have triplicates of multiple songs and ca
-
Error while doing VL10B(PGI)
Dear all, I maintained the batch for the material e.g for one material three batches and i have done the 501 for the same. and created STO for that material n also SD doc is created,while doing VL02N (outbound deliv ) when i am doing the Batch split
-
Unable to Install Windows 7.0 64 bit on Hp Pavilion i3 Model 15-00B002tu
Hi, This is Related with my Hp Pavilion I3 Model i5-00B002tu, Which Came with Win 8.0 Pre-Installed,Problem is that Iam Trying to Load Windows 7.0 64 bit From Usb but at the end of the installtion it gives me the error "Windows setup could not co
-
TS1538 iPhone not recognised by Desktop PC
After completing all of the instructions regarding my iPhone not being recognised by My Computer and, subsequently, iTunes it is still not working. A couple of extra things: 1. The iPhone in question can plug into my laptop and is recognised 2. Anoth
-
Forms (displaying all code on response email)
Hi guys, I've recently been using the new forms feature but have an issue!! When someone sends an enquiry via my website, the response email I get displays correctly on my mac but not on pc or webmail? any suggestions please?