www.techdos.com Oracle Develop an application in C / C + + with the library OCILIB Wednesday, 14 May 2008 III. Installation III-A. Nearly required Having a system like Unix or Microsoft Windows supported by Oracle Have an Oracle client installed (not required for compilation, but for the execution) III-B. Compatibilities The following platforms have been validated (compilation, installation, build and implementation of a project): Microsoft Windows Linux Solaris HP / UX AIX The other platforms supported by Oracle (MacOS server, OpenVMS, z / OS) have not been officially tested, but in view of platforms already validated, it should not be too problematic! The compilers have been validated following: Microsoft Compilers (VC + +, VS200X) GCC and MinGW XLC CC owners The following versions of Oracle (clients and servers) have been validated: Oracle 8i Oracle 9i Oracle 10g Oracle 11g III-C. Installation under Unixes (Unix / Linux / Mac) OCILIB uses the GNU tools for its deployment and installation. Extracting the current archive (ocilib-xyz-gnu.tar.gz) $ Ocilib CD-x.y.z $. / Configure $. / Make $. / Make install (generally, you have to go to root for installation) Check environment variable paths dynamic libraries (LD_LIBRARY_PATH, LD_PATH, ..) so the directory of shared libraries Oracle is there and that is where installed OCILIB (typically / usr / local / Lib Linux) Typically, just add to its roster. Profile: > Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH: $ ORACLE_HOME / lib: / usr / local / lib OCILIB supports 3 installation options: -- with-oracle-import = (linkage | runtime) -- with-oracle-charset = (ansi | unicode | mixed) -- with-oracle-home = (oracle directory) III-D. Installation under Microsoft Windows Under Microsoft Windows, DLLs are provided for 32bits environment and 64bits (x86) and can be recompiled easily. Extracting the current archive (ocilib-xyz-windows.zip) Copy ocilib \ src \ ocilib.h in a directory included in the list to "file headers" compiler Copy ocilib \ lib32 | 64 \ ocilib [x]. Lib in a directory included in the list to "file library" of the editor link Copy ocilib \ lib32 | 64 \ ocilib [x]. Dll files in a directory included in the PATH http://techdos.com Powered by Joomla! Generated: 21 July, 2011, 13:48 www.techdos.com [x] represents the compiled version of OCILIB: "a" for Ansi, "w" for Unicode and "m" for mixed mode III-E. Setting up projects To use OCILIB in a project must include the header "ocilib.h." Some options must be defined before the inclusion of header ocilib.h => Mode liaison Oracle: OCI_IMPORT_LINKAGE: to link libraries (static or shared) the compilation (default Unix like) OCI_IMPORT_RUNTIME: to load dynamically bookstores oracle in execution (default option under MS Windows) => Charsets used: OCI_CHARSET_ANSI: any strings are Ansi (default) OCI_CHARSET_UNICODE: any strings are Unicode (versions of Oracle> = 9i) OCI_CHARSET_MIXED: Orders SQL, metadata to Ansi and user data supplied and recovered queries Unicode => Convention of Appeal (MS Windows only): OCI_API: not defined (default) OCI_API: __sdtcall to use dll precompiled On Windows, for use in OCILIB ANSI, using Dlls provided, it is enough to create a new project: Include "ocilib.h" Defining OCI_API = __sdtcall in options preprocessor Project If all variations ocilib [x]. Lib are available for the linker, then specify which version by inserting # pragma comment (lib, "ocilib [x]. Lib") in a file Project In Linux for use in OCILIB ANSI and with a linkage of shared libraries to the compilation, it requires: => Include "ocilib.h" => Add to makefile for compilo: -I/usr/local/include For the header ocilib.h - DOCI_IMPORT_LINKAGE-DOCI_CHARSET_ANSI to configure ocilib => Add to makefile for the linker: - L / $ ORACLE_HOME / lib-lclntsh bookstores for Oracle -L/usr/local/lib-Locilib for the library OCILIB IV. Log Oracle IV-A. Initialize OCILIB Above all else, OCILIB be set. This requires, first and foremost appeal to a function of the library, call OCI_Initilalize (). This feature makes the library and takes parameters: [Optional] A pointer to a function of management errors [Optional] A directory or is bookstores Oracle (if runtime loading and several customers Oracle installed) [Optional] mode initialization. Currently, only the value is supported OCI_ENV_DEFAULT Example # include "ocilib.h" int main () ( if (OCI_Initialize (err_handler, NULL, OCI_ENV_DEFAULT) == FALSE) Return EXIT_FAILURE; / * ... code application ... * / OCI_Cleanup (); http://techdos.com Powered by Joomla! Generated: 21 July, 2011, 13:48 .techdos. sql_code. * / OCI_FreeConnection (cn).. / * . OCI_ErrorGetString (err)). an appeal to OCI_Cleanup () is required to: Desallouer objects not explicitly released Download Oracle bookstores in the case of a runtime loading IV-B. OCI_SESSION_DEFAULT). Example OCI_Connection * CN. code application ..com return EXIT_SUCCESS. "password". create a session and establish a transaction.. if (cn! = NULL) ( printf ( "% s \ n". Example of a function of management errors that merely display on the screen an SQL error: ErrorHandler void (* OCI_Error err) ( int sql_code = OCI_ErrorGetOCICode (err). . * / cn = OCI_CreateConnection ( "Database". OCI_SESSION_SYSOPER) This function of charge to connect to server. ) At the end of the application.. ) / * . Error Handling OCILIB proposes a mechanism for handling errors based on the concept of callback to be triggered in the following cases: Error processed by OIC Error allocating memory Error internal OCILIB The prototype of the function is to provide as follows: typedef void (* POCI_ERROR) (* OCI_Error err). "user".. / * .. http://techdos. just call OCI_FreeConnection () IV-C. 13:48 . If successful.com Powered by Joomla! Generated: 21 July.. SID. Connections Connect to an Oracle database is done by the function OCI_CreateConnection () which takes parameters: The office Oracle (aka Oracle. The name of the user Oracle on which to connect The password from the user Oracle The mode of session (OCI_SESSION_DEFAULT. * / To close connection to the server. A handle on an object OCI_Error is then provided to the function.... it returns a handle connection and the application can immediately execute orders SQL. OCI_SESSION_SYSDBA..www. within the parameters of the Oracle client). The library provides functions to access the properties of the error generated. OCI_GetVersionServer (cn)). 2011. if (sql_code! = 0) ( printf ( "Code: ORA-05i% \ n" "Msg:% s \ n". LONG RAW.. VARCHAR2/NVARCHAR2. INTERVAL_YM. TIMESTAMP_LTZ OCI_Timestamp INTERVAL. Transactions OCILIB support mechanisms transactions (local and global) proposed by Oracle via OIC. . NUMBER . There are cases where simple transactions local default is not enough: manage a connection to read only by example manage a global transaction in a distributed environment etc. VARRAW.. dtext * (char * or wchar_t * by the build) Numbers without precision (whole): INT. VARCHAR2/NVARCHAR2.. NUMBER. and link it to handle a connection. CFILE Types LONGs: LONG... VARRAW.. By default.com ) ) IV-D. delete) are not visible from other sessions as it was not explicitly endorsed the changes by a call to OCI_Commit (). big ints (signed / unsigned) Boat: FLOAT. OCI_Long BLOB / CLOB / NCLOB OCI_Lob DATE OCI_Date TIMESTAMP. Types of data supported OCILIB supports all types of data provided by Oracle. . Large Objects (Lobs and Files): BLOB. .. Date. IV-E.com Powered by Joomla! Generated: 21 July.. INTERVAL_DS OCI_Interval PL / SQL Ref Cursors OCI_Statement PL / SQL Nested Tables OCI_Statement User Types OCI_Object ROWID dtext * (char * or wchar_t * by the build) http://techdos. TIMESTAMP_TZ. except for references and collections. VAR LONG. update. If the application does not validate its changes and thus nullify the data changes made since the last validation (or default from the server connection). double RAW void * LONG. ints. . REAL NUMBER (X.. CLOB.. shorts.. Oracle TYPE Type OCILIB Strings: CHAR / NCHAR. TIMESTAMP (all) INTERVAL (all) PL / SQL types: Ref cursors and Nested Tables Names Types: User types. ROWIDs All of these types may be incurred related to statements or be recovered from a select. Y).. .... once the application was connected to Oracle. FLOAT. LONG RAW. 13:48 .): CHAR / NCHAR. . a local transaction is created.. . Timestamps and Intervals: DATE.. NCLOB.. it must use OCI_Rollback (). List of types supported: All types scalar (strings. Any modification of data (insert. LONG RAW .techdos. digital floating . In these cases.. Types binary: RAW. XmlType.www. OCILIB proposes an explicit management transactions where it is possible to create a transaction. 2011. BFILE. OCI_Statement * st. V-B. Once this object creates. OCI_FreeStatement (St). 2011. "delete from test_fetch where code = code"). OCI_GetAffectedRows (st)). Linking variables In the previous example. OCI_Commit (cn). OCI_Prepare (st. it is possible to run queries on the function OCI_ExecuteStmt (). 13:48 . * / OCI_ExecuteStmt () has prepared and carried out the order and SQL OCI_GetAffectedRows () has recovered the number of lines deleted from the table. code = 56. & code)..). / * . the query was simple and not require any input variable. Carry out orders SQL V-A. a call to OCI_FreeStatement () frees all resources associated (resultset.. Once the statement is more useful.. Example OCI_Connection * CN. SQL Statements To execute orders on the SQL database.com V. OCI_GetAffectedRows (st)). A OCI_Statement object can be reused to execute as many orders as necessary SQL.com Powered by Joomla! Generated: 21 July. it requires: Prepare SQL OCI_Prepare () Linking variables with the functions OCI_bindXXX () or XXX is the type of data Execute SQL OCI_Execute () Example OCI_Connection * CN. "delete from my_table where code is null"). code = 3. OCI_Statement * st. * / st = OCI_CreateStatement (cn). OCI_Execute (St). / * . OCI_GetAffectedRows (st)).techdos. it is useful to be able to execute several times a similar SQL with different values without having to repreparer SQL by Oracle to optimize performance.. printf ( "% d row deleted". printf ( "% d row deleted.. In this case. it is necessary to provide a request values entries not known in advance.. OCI_ExecuteStmt (st. Often.. / * . we have to create an object SQL statement via function OCI_CreateStatement (). * / st = OCI_CreateStatement (cn). OCI_BindInt (st. int code. It is therefore possible to link variables of the programme by providing their address to the statement. "code". Moreover. . OCI_Execute (St)..www. http://techdos. printf ( "% d row deleted. .techdos. ) OCI_Commit (cn)..com Powered by Joomla! Generated: 21 July. value. 2011.. "value% i". 20). "name% i". "select * from test_fetch"). 30). * / st = OCI_CreateStatement (cn).www. "insert into my_table values (code. / * . "value". it requires: Browsing the resultset by a call to OCI_FetchNext () which returns TRUE as there are lines result Calling a function OCI_GetXXX () specifying the index of the column (or his name) and where XXX is the type: Int. OCI_BindInt (st... * / To make a mass insertion.: name. Oracle supports "bulks operations" (see Chapter VI) which can manipulate arrays and provide unparalleled performance. 13:48 . name. "name". & code).. Just after the statement executed via OCI_Execute () or OCI_ExecuteStmt () call function OCI_GetResultSet () which returns a handle on an object OCI_Resultset. sprintf (value. http://techdos. char name [30]. V-C. OCI_ExecuteStmt (st. OCI_BindString (st. code <10000.. OCI_Statement * st. OCI_Resultset * rs. OCI_Statement * st. char value [20]. This includes 2 resultset things: The description of the columns returned by the query The data (lines results) To access the values of each column in the resultset. OCI_Prepare (st. OCI_Execute (St). int code. / * . code + +). Get the result of a select Get the result of a complaint is very simple. / * . String. code). Date. "code". we can proceed as follows: Example OCI_Connection * CN. Example OCI_Connection * CN. .. code).. OCI_BindString (st. / * .. * / Nevertheless. ( sprintf (name. for (code = 1.com OCI_Commit (cn).: value)"). * / st = OCI_CreateStatement (cn). * / OCI_GetRowCount () gives the number of lines of resultset already covered. * / st1 = OCI_CreateStatement (cn). OCI_Prepare (st2. while (OCI_FetchNext (rs)) ( printf ( "code:% i. OCI_GetInt (rs. / * . Example OCI_Connection * CN. OCI_GetString (rs. OCI_Statement * st. OCI_ExecuteStmt (st. "ACTION") OCI_GetDouble2 (rs. * / st = OCI_CreateStatement (cn). ) printf ( "\ n% d row (s) fetched \ n". rs = OCI_GetResultset (st). "delete from my_table2 where code_ref =: Code"). OCI_GetRowCount (rs)).com Powered by Joomla! Generated: 21 July. & code).. The same example with access to columns by their names: Example OCI_Connection * CN. / * . / * .. "PRICE").techdos. OCI_GetString2 (rs. OCI_GetRowCount (rs)). OCI_ExecuteStmt (st1. price:% g date% s \ n".. OCI_GetString (rs. OCI_GetStrin2g (rs. 1).. rs = OCI_GetResultset (st).. 4)). 2011.www. 2) OCI_GetDouble (rs 3). while (OCI_FetchNext (rs)) http://techdos. 13:48 . * / A statement object can be reused as many times as you want. it is possible to create multiple and the nest. "DATE")). OCI_Statement * st1. "CODE").. "code". OCI_GetInt2 (rs. "select code from my_table"). action:% s. price:% g date% s \ n". st2 = OCI_CreateStatement (cn). OCI_Resultset * rs... "select * from test_fetch"). / * . * st2. Moreover. OCI_Resultset * rs.. action:% s. ) printf ( "\ n% d row (s) fetched \ n"..com rs = OCI_GetResultset (st). OCI_Bind (st2. int code. while (OCI_FetchNext (rs)) ( printf ( "code:% i. OCI_GetColumnCount nb = (rs). OCI_Statement * st. * / V-D. i).. OCI_Execute (st2). OCI_Execute (St). / * . ) / * . & n). rs = OCI_GetResultset (st). ) / * . i <= # i + +) ( col = OCI_GetColumn (rs. OCI_BindInt (st.com ( OCI_GetInt code = (rs. * / st = OCI_CreateStatement (cn)...techdos.. "select * from my_table"). "n". OCI_Column * col. for (i = 1."). OCI_ExecuteStmt (st. Example of a block PL / SQL OCI_Connection * CN. OCI_Statement * st. OCI_Prepare (st. it is sufficient to cover the PL / SQL by a "begin" a beginning and an "end" in the end block. To do this: A call to OCI_GetColumnCount () can see the number of columns contained in the resultset A call to OCI_GetColumn () specifying index (position in the select) to get a handle on an object OCI_Column All properties of the column are accessible by a series of functions type OCI_GetColumnXXX () where XXX is the property Example OCI_Connection * CN. 13:48 . To execute PL / SQL. 1)..com Powered by Joomla! Generated: 21 July.www. end.. printf ( "%-20s-10s% 8i%-%-%-8i-8i% s \ n". http://techdos... OCI_GetColumnName (Col) OCI_GetColumnSQLType (Col) OCI_GetColumnSize (Col) OCI_GetColumnPrecision (Col) OCI_GetColumnScale (Col) OCI_GetColumnNullable (Col) == TRUE? "Y": "N"). "begin: n: trunc = (sysdate 1)-trunc (sysdate-1). * / st = OCI_CreateStatement (cn). * / It is possible to retrieve information on (metadatas) each column of resulset (columns selected by the application). OCI_Resultset * rs. PL / SQL blocks Variables can be linked both input and output. 2011. / * . . end.www. OCI_Statement * st. 1)). thus reducing the number of trips between the client and server. each entry of the table may affect different lines. OCI_Prepare (st. OCI_RegisterInt (st.. * / Sample recovery of "a cursor PL / SQL and fetch his result in the program C: Example OCI_Connection * CN. OCI_Statement * st. resultset following is recoverable by a call to OCI_GetNextResultset ().com printf ( "Result:% i \ n". OCI_BindStatement (st. / * . OCI_GetString (rs. This resultset is then manipulated as a classic resultset. the application indicates explicitly columns of the clause by RETURNING functions OCI_RegisterXXX () or XXX is the type of data... Once this resultset come. OCILIB not ever pre-parse the SQL (for performance reasons) and therefore can not determine the fields (and their type) used in the clause RETURNING. OCILIB then resultsets built on the basis of columns and reported. ) / * . For example. * / St = OCI_CreateStatement (cn). "i"). "c". st2).. The Array Interface is also compatible with this clause..techdos. the application begins with the first resulset recover with a call to OCI_GetResulset (). OCI_Prepare (st. "my_table set update content = content | | to_char (code) returning code. Therefore." The use of this clause in a DML (insert / update / delete) can combine 1 to 2 requests. * / st = OCI_CreateStatement (cn). http://techdos. if the table used to link variables statement contains 100 items.. This is convenient. The addition of this clause can select the lines affected by the DML within the same request. OCI_Execute (St). "begin open: c for select * from my_table. / * . * / V-E. 2011. OCI_Resultset * rs. rs = OCI_GetResultset (st2)."). 13:48 .. Example selection of objects of a table: OCI_Connection * CN. / * . n). Support of the clause SQL RETURNING Oracle offers a very interesting feature which is the SQL clause "into returning. In this case.com Powered by Joomla! Generated: 21 July. while (OCI_FetchNext (rs)) ( printf ( "my name is% s \ n". st2 = OCI_CreateStatement (cn). OCILIB creates a resultset for each entry of the table. content into: i: s"). especially in the case of delete deleted because the values are recoverable! OCILIB implements this feature by creating an object OCI_Resultset from selected columns in the clause RETURNING. OCI_Commit (cn). / * . Bulk Operations The "bulk operations" are a very powerful feature supported by Oracle. it may be long! Oracle therefore proposes a simple solution that allows you to obtain optimal perfomances: OIC Interface Array VI-A. / * Fetch data changed * / Rs = OCI_GetResultset (st). ) Printf ( "count:% i \ n". 2011..www. 2)). it provides an array of 10000 values which is sent at once. 50). Check statements OCILIB proposes a series of functions to customize the behaviour of a statement. it is possible to: prepare the complaint variables are linked wrap 1 to 10000 to execute the SQL bearing in each round loop updated values. network traffic generated by a large number of executing a single complaint is the main source of the slow final treatment. which can make massive updates (insert / update / update) tables in record times. Instead of providing 1 variable and send 10000 times its value to the server. In a pattern. VI. Oracle proposes to minimize this traffic by providing arrays. OCI_GetRowCount (rs)). / * Updated data * / OCI_Execute (St). The system reduces the processing time by factors of 3 to 5 digits at least on large volumes. * / V-F. 1).com OCI_RegisterString (st. Oracle Array interface In the previous example.content:% s \ n". .techdos. For example. OCI_GetInt (rs. CI_GetInt (rs. This scheme will generate 10000 calls for execution of the request and therefore round 10000 / returns with the server for: Transmitting values Run again SQL All these calls and round / network returns are costly in terms of performance! If you want to add 1 million lines.com Powered by Joomla! Generated: 21 July.. it is possible to specify: The number of lines pre-fetchees by the Oracle client to reduce the number of roundtrips to the server The number of lines fetchees internalement by OCILIB to reduce calls OIC The mode of binding of variables: by name or position The date format default Etc.. OCILIB supports this mechanism and the possibility of linking tables of any type supported by OCILIB (except OCI_Long and OCI_Statement) http://techdos. if you want to insert 10000 rows in a table for example. 13:48 . While (OCI_FetchNext (rs)) ( printf ( "code:% i . "s". * / VI. / * . 10000). OCI_BindArrayOfStrings (st. OCILIB also supports the former implementation LOBs: the types LONG. ) / * * Execute / OCI_Execute (St). LONG RAW and RAW. 20). always maintained by Oracle. sprintf (tab_str [i].techdos. * / OCI_Prepare (st. "s". "Name% d". / * Filling arrays * / for (i = 0. "i". i + +) ( tab_int [i] = i +1.com VI-B. i +1). For example.. Internal Objects (LOBs) The BLOB / CLOB are stored in the database. 13:48 .com Powered by Joomla! Generated: 21 July. There are basically 2 types of large objects: The BLOB / CLOBS: objects stored in binary form (BLOBS) / text (CLOBS) The BFILES: objects not stored within the DB. OCI_BindArrayOfInts (st. ... The types LONGs are still currently employed in the very bases and Oracle applications. Indeed. char tab_str [10000] [21]. That is why OCILIB proposes an API very close to those of LOBs (while the sub layer OIC management LONGs is very different from that of LOBs). i <10000. 2011. Using Large Objects Oracle 8 introduced LOBs (Large Objects) to store and manipulate large objects size (> several GB) to meet the storage needs of large files (multimedia.. are "ancestors" of LOBs and accounted for in earlier versions (up to Oracle 7) the only way to store large volumes (but more limited) in the DB. These types. OCI_Statement * st. OCILIB offers a variety of functions can easily manipulate these objects (OCI_Lob *). Examples Example for inclusion in one fell swoop 10000 rows in a table: OCI_Connection * CN. OCI_Statement * st. / * . Their use differs from those of other types of data. Moreover. to insert the contents of a file in a field BLOB a table: OCI_Connection * CN. tab_int). a simple SQL does not read or write in a field of several hundred Mo. "insert into my_table values (: i: s)"). VI-A. video.www. OCI_GetAffectedRows (st)). http://techdos... tab_str. These are pointers to files accessible by the server (on the same file system or not) and are manipulated by the client application OCILIB fully supports these types of data. printf ( "row processed:% d \ n". * OCI_Lob lob.) and the raw data Within the DB. int tab_int [10000]. OCI_BindArraySetSize (st. OCI_BindLob (st. printf ( "\ nTotal bytes to write:% d \ n". f))) ( OCI_LobWrite (lg. OCI_Resultset * rs. OCI_LobCreate lob = (cn. 1). fclose (f).techdos. 13:48 . ) printf ( "\ nTotal bytes written:% s \ n". 1. "data". unsigned char buffer [1024]. OCI_Statement * st. while (OCI_FetchNext (rs)) ( OCI_GetLob lob = (rs.www. OCI_BLOB).com FILE * f. if (f! = NULL) ( fseek (f.. "insert into my_blob_table (code. SEEK_END). * / st = OCI_CreateStatement (cn). size). buffer. rs = OCI_GetResultset (st). to read the contents of a text file ANSI stored in a field of CLOB type of a table: Example OCI_Connection * CN.. OCI_Execute (St).com Powered by Joomla! Generated: 21 July.. int size. n). char buffer [128]. * / st = OCI_CreateStatement (cn). / * .. content) values (1. ) / * . Rewind (f). OCI_LobGetLenght (lob)). "select content from my_blob_table where code = 1"). FILE * f. lob). OCI_Prepare (st. "rb").: data)"). / * Write data into table by chunks of 1024 bytes * / while ((n = fread (buffer. f = fopen ( "My file". 0. OCI_LobFree (lob). * / For example. / * Read data from table by chunks of 128 bytes * / while ((n = OCI_LobRead (lob. OCI_Commit (cn).. buffer. sizeof (buffer). size = ftell (f). * OCI_Lob lob.. OCI_ExecuteStmt (st. / * . 2011. sizeof (buffer) -1)) http://techdos. OCI_Statement * st. OCI_FileOpen (file).. OCI_ExecuteStmt (st. unsigned char buffer [1024]. OCI_Statement * st. "select value from my_bfile_table where code = 1").. 2011. Sample reading of a field BILE an Oracle table: OCI_Connection * CN. * / VI-B. OCI_File * file. OCI_FileGetDirectory (file)). * / st = OCI_CreateStatement (cn).. 13:48 ..techdos.. printf ( "file dir% s \ n". sizeof (buffer)) ( / * Do what you want content . int n. http://techdos. while (n = OCI_FileRead (file. Examples to store a binary file in base and then retrieve the content: OCI_Connection * CN. Long Objects OCILIB implements the "old" LONGs (OCI_Long *) similarly to the LOBs and FILEs. OCI_Resultset * rs. printf ( "file size% d \ n".com Powered by Joomla! Generated: 21 July. buffer). The APIs handling LONGs fields are very close to those of Large Objects. printf ( "file name% s \ n". 1).. OCI_Long * LG. ) ) / * .. int n. unsigned char buffer [1024]. FILE * f.www. / * . OCI_Resultset * rs. ) / * . while (OCI_FetchNext (rs)) ( file = OCI_GetFile (rs. * / VI-C. rs = OCI_GetResultset (st). * / ) OCI_FileClose (file). printf ( "% s \ n".com ( buffer [n] = 0.. The objects FILEs are similar to the LOBs and therefore their API is similar except that FILEs are read-only. OCI_FileGetName (file)). External Objects (FILEs) The objects of type FILE (OCI_File *) are references to external files to the DB that can be opened for reading by the server and whose content can be retrieved by the client application. OCI_FileGetSize (file)). buffer. OCI_LongGetSize (lg)). ) / * . 1). if (f! = NULL) ( fseek (f.. OCI_Execute (St). buffer. * / st = OCI_CreateStatement (cn).. f))) ( OCI_LongWrite (lg. OCI_Prepare (st. "insert into test_long_raw (code. fclose (f). n). 2011. lg = OCI_LongCreate (st. OCI_BindLong (st.: data)"). OCI_LongGetSize (lg)). OCI_SetLongMaxSize (st. "rb").. buffer. / * Write data into table by chunks of 1024 bytes * / while ((n = fread (buffer. n = ftell (f).. OCI_BLONG). ) / * Retrieving data from DB * / OCI_ExecuteStmt (st. 13:48 . A "TYPE" oracle is seen as the equivalent of a C. ie types of data appointed created by the user or provided by Oracle.com / * . / * Storage file in the DB * / f = fopen ( "file name". "select content from test_long_raw where code = 1"). while ((n = OCI_LongRead (lg.www. 1. content) values (1. SEEK_END). "data".com Powered by Joomla! Generated: 21 July. OCI_Commit (cn). sizeof (buffer)))) ( / * Do what one wants data * / ) printf ( "\ n% d bytes read \ n". Example of creating a type of data: Create as object type t_produit http://techdos. sizeof (buffer).. * / VIII.techdos. printf ( "\ n% d bytes to write \ n".. 100000). / * Read data by chunks of 1024 bytes * / while (OCI_FetchNext (rs)) ( lg = OCI_GetLong (rs. ) printf ( "\ n% d bytes written \ n". 0. OCI_LongFree (LG). Handling Named Types OCILIB poropose "Named types". n). rs = OCI_GetResultset (st). It is an aggregation of fields types scalar or aggregated. Rewind (f). lg n). : n: d)"). http://techdos. OCI_BindDate (st. printf ( "\ n% d row (s) inserted \ n". OCI_Prepare (st. "USB KEY 2go"). libel varchar2 (30).99). OCI_Commit (cn). OCI_Execute (St). OCI_GetAffectedRows (st)).www. prod). OCI_Statement * st. / * . OCI_BindInt (st. Int number. * / VIII-B. "CODE".. 1). "t_product" OCI_SCHEMA_TYPE).. / * . 13:48 . "REFERENCE". "PRICE". "insert into ventes_produits values (p. "n". OCI_ObjectSetInt (prod. Example create an instance of an object for insertion into a table: OCI_Connection * CN. OCI_Date * date. & qty). OCI_BindObject (st.3). "p". OCI_ObjectSetString (prod. This is achieved by a call to OCI_SchemaGet (). qty = 356. price number (5. "d". "A56547WSAA"). OCI_ObjectSetString (prod. Selecting objects Objects can be selected in the same way that SQL data types. OCI_DateSysDate (date). OCILIB can: create instances of objects linking objects to SQL select items from one table manipulate the attributes of an object VIII-A. OCI_Object * Prod. OCI_SchemaGet (cn. OCI_ObjectSetDouble (prod. * / OCI_ObjectCreate prod = (cn.com ( code number.. REFERENCE varchar2 (100) ).techdos. 2011.. int QTY. 12. date). we must recover the descriptor of the type concerned. date = OCI_DateCreate (cn). "LIBELLE". create table ventes_produits ( T_produit product. Autonomous Bodies To create an autonomous body. Date_vente date ). OCI_ObjectFree (obj).com Powered by Joomla! Generated: 21 July. ) IX-B. Example where a date is recovered from a table. OCI_Object * Prod. OCI_DateToText (dt. while (OCI_FetchNext (rs)) ( dt = OCI_GetDate (rs.techdos.com Powered by Joomla! Generated: 21 July. / * . 1).. char str [100]. while (OCI_FetchNext (rs)) ( OCI_GetObject prod = (rs. OCI_DateToText (dt. OCI_ExecuteStmt (st. "LIBELLE"). str). sizeof (str) -1. OCI_Resultet * st. OCI_GetDate date = (rs. * / OCI_ExecuteStmt (st. / * . rs = OCI_GetResultset (st). Timestamps The timestamps are extensions to the type DATE: http://techdos. 1). sizeof (str) -1. 2). * / IX. "select mon_champs_date from my_table"). OCI_Resultset * rs. 2).www. OCI_DateAddMonths (dt.. ) / * . incremented by 5 days and 2 months and then redisplayed: Example OCI_Statement * st. qty). 5)... 3). Dates OCILIB capable of handling dates Oracle (time) with ease. OCI_Date * date. Handling dates and timestamps IX-A. printf ( "Product:% s. OCI_ObjectGetString (prod. str). "select * from ventes_produits"). OCI_GeInt qty = (rs. str). OCI_Statement * st.. OCI_DateAddDays (dt.. int QTY. 13:48 . "DD / MM / YYYY HH24: MI: SS". printf ( "Date is% s \ n". printf ( "Date + 5 days and 2 months is% s \ n". rs = OCI_GetResultset (st). Sales:% i \ n". * / st = OCI_CreateStatement (cn).com Example selection of objects of a table: OCI_Connection * CN. OCI_Date * DT. "DD / MM / YYYY HH24: MI: SS". 2011. str). then displayed. 0).. Example where time is running local recovered in variable tm. OCI_IntervalSetDaySecond (ITV. OCILIB for builds Unicode. 10.techdos. ITV OCI_IntervalCreate = (cn. To go further X-A. initiates OIC UTF16 mode. hours.1. 10. which is implemented by Oracle by encoding a fixed size of 2 bytes. OCI_TimestampIntervalAdd (tm. char str [100].www. printf (STR). OCI_TimestampToText (tm. * OCI_Timestamp TM. 3)..com Powered by Joomla! Generated: 21 July. OCI_IntervalToText (ITV. 100. tm = OCI_GetTimestamp (rs. printf (STR). OCI_TimestampSysTimeStamp (TM).. * OCI_Timestamp TM. OCI_Interval * ITV. 1.com manage the exact dates through the management of fractions of seconds manage timezones Example where time is running recovered server and displayed with fractions of seconds: Example OCI_Statement * st. OCI_INTERVAL_DS). / * . OCI_ExecuteStmt (st. 1 minute and 1 second and then displayed with fractions of seconds: Example OCI_Connection * CN. "DD / MM / YYYY HH24: MI: SS: FF3 \ n". OCI_TimestampToText (tm. str. printf (STR). rs = OCI_GetResultset (st). / * . X. * / st = OCI_CreateStatement (cn). Support Unicode OCILIB fully supports Unicode on all platforms across the data type C wchar_t (UTF16/UTF32 according platforms).1. OCI_FetchNext (rs). str.. 1 hour. char str [100]. 2011. Intervals The intervals are periods of time expressed: either in years and months either in days. ITV). 1).1. then incremented by 1 day. minutes and seconds They can perform operations on timestamps. IX-C. OCI_TIMESTAMP_TZ). 13:48 . 100. str. "DD / MM / YYYY HH24: MI: SS: FF3 \ n". http://techdos. "SELECT FROM dual CURRENT_TIMESTAMP"). 3). * / OCI_TimestampCreate tm = (cn. 100). ) allocates its buffers on the size of wchar_t and execute an expansion of UTF16 a UTF32 for buffer data The expansion of data is "inplace. OCI_GetColumnPrecision(col). OCI_GetColumnScale(col). /* . if (tbl) { printf ("Column Name Type Length Prec. "MyTable". Scale Null ?\n").------------------------------\n"). Functions "All In One" OCILIB offers functions "all in one" who have a list of arguments variables. wchar_t is implemented on 4 bytes and UTF32 is usually used as encoding. OCI_GetColumnName(col). */ X-C. OCI_GetColumnSize(col). n = OCI_SchemaGetTableColumnCount(tbl). on systems implementing wchar_t on 2 bytes (MS Windows). X-B. */ tbl = OCI_SchemaGetTable(cn. For example: OCI_Connection *cn. 2011. } /* . attributes. printf ("---------------------------.www. } } OCI_SchemaFreeTable(tbl).. On other systems (almost all Unix and Linux). . for(i = 1. OCI_GetColumnSQLType(col). i++) { col = OCI_SchemaGetTableColumn(tbl. OCILIB: uses buffers to pass a temporary OIC strings of characters of meta-data (queries.techdos. They reduce the number of lines of code to the minimum possible! For example. 13:48 . Describe the tables a scheme OCILIB allows Decrire tables of a scheme. OCI_GetColumnNullable(col) == TRUE ? "Y" : "N"). i)." which has the advantage of not requiring additional buffer. i <= n. strings and buffers users are passed directly to Oracle... OCI_Schema *tbl. This helps to optimize the better management of variable size type wchar_t. int n... FALSE).com So. In this case. OCILIB can write to 1 single line of code the following actions: Preparation of SQL Liaison a variable Execute the statement Fetch the result (1 line) This is equivalent to the following code: http://techdos.com Powered by Joomla! Generated: 21 July. printf("%-20s%-10s%-8i%-8i%-8i%-s\n". 1). /* . code. /* . OCI_ExecuteStmtFmt(st. & code).*/ OCI_Immediate(cn. use clause "into Returning" Adjust the number of lines per fetch with OCI_SetFetchSize () Adjust the number of lines préfetchées by the server with OCI_SetPrefetchSize () Prefer the Lobs and the LONG LONG RAW To retrieve the values of a resultet use access by index instead access by name columns in order to avoid the use of maps index / name XII.. one fetch) ------------------------------. Documentation Consult the documentation online Download the online documentation XI. OCI_GetResultset (St). OCI_ARG_TEXT.. code. OCI_Bind (st. Optimize performance => Some tips to optimize the maximum performance: Avoid OCI_xxxFmt function () because.techdos. 13:48 . OCI_Statement *st. */ /* sql immediate (parse. &code. rs = OCI_GetResultset(st). */ /* sql format with params ----------------------------------------------. "select code.com Powered by Joomla! Generated: 21 July.. code).*/ st = OCI_CreateStatement(cn). OCI_ARG_TEXT.. OCI_GetString (rs. OCI_FetchNext (rs). name). variables are linked with OCI_Bindxxx () and then execute it as many times as desired with OCI_Exectute () If possible. name).com OCI_Prepare (st.. name). OCI_ARG_TEXT. OCI_Execute (St).www. OCI_ARG_INT. /* . */ /* sql immediate (parse.. code. /* . "select article from test_fetch where code =% i".. 2011. "select * from test_fetch where code = %i". article from test_fetch where code = 1". Download http://techdos.. use tables to link variables If the values affected by a DML must then be resélectionnées. exec. printf("code %i . "code". "select article from test_fetch where code =: i"). name). it is better to prepare once with OCI_Prepare (). although very practical. Other examples: Exemples OCI_Connection *cn. OCI_Resultser *rs. exec. printf("article : %s\n"). they require a parsing of the order and a SQL formatting variables that can be costly if the complaints are executed many times If an order SQL must be repeated several times.article : %s\n".*/ OCI_ImmediateFmt(cn. Who can be replaced by the following code: OCI_ImmediateFmt (cn. */ X-D. "select article from test_fetch where code = %i". one fetch) with params ------------------. name). .. 8i. VARCHAR2/NVARCHAR2. NCLOB. threads and mutexes Error Handling Global Transactions Data Links Statements reusable SQL Description of a pattern Access to a select columns by position or by name Bulk operations (array interface): insert / update / delete liaison with arrays to accelerate performance Management simple reads / writes in the fields LONG / LOBS Support PL.4. The interface of this library has been designed to: Being the simplest possible Propose the wealth of OIC Reducing the number of lines of code and call functions necessary Propose functions with the least possible parameters Respect the principle of encapsulation to pérénniser the library (which is why no structure data is public.www.com Powered by Joomla! Generated: 21 July.. Date. Refs) All types scalar (strings. ref cursors Nested tables XIV. . .. Conclusion OCILIB can develop easily and effectively implementing Oracle in C / C + +. CLOB. Large Objects (Lobs and Files): BLOB.. This tutorial flew in broad library OCILIB. for example) OCILIB currently does not implement fully OIC in the sense that certain features such as Refs.): CHAR / NCHAR. 10g. 11g Support across relational API provided by OIC Partial support of the API object provided by OIC + 310 simple functions Pools of connections API portable hash tables. LONG RAW. LONG VAR. 13:48 . The HTML documentation provides more details and includes features not mentioned in this article. BFILE. CFILE Type LONG (piecewise operations): LONG. It is an open source library and everyone can if it wishes to change the library to its own needs and let others benefit. are not supported.. 2011. 9i. http://techdos. FLOAT. queues. VARRAW.0) Here is a non-exhaustive list of main features to the date of the article: => Library: Pur ISO code C (C90 and C99 to support Unicode) Portable on all platforms supported by Oracle API simple and compact Support Unicode complete Supports dynamic loading bookstores Oracles (hence Oracle is not required to compile) Consumption reduced memory Provides hash tables => Type of data: Support of all types of data Oracle (except collections. Features (version 2. collections. .. . digital floating . XIII.. NUMBER.techdos. Types binary: RAW. TIMESTAMP (all) INTERVAL (all) PL / SQL types: Ref cursors and Nested Tables Named Types: types users and types systems ROWIDs => Features: Compatible with Oracle 8. SQL block. Timestamps and Intervals: DATE.com Available at: OCILIB Project page on the site Sourceforge. com Powered by Joomla! Generated: 21 July.0. 2011.com The current roadmap is as follows: Version 3. 13:48 .www.net) XV.techdos.H (for its bars magic levels of difficulty) http://techdos.0: Support comprehensive API Object Relationnal (References. vince_del_paris (sourceforge. Acknowledgments Corrections RideKick Formatting Franck.com). Queues/SubscriptionsContact the author (Vincent Rogier): vicenzo (developpez. Collections).