Oracle C++ Call Interface Programmer's Guide Release 2 (9.2) Part Number A96583-01 |
|
Oracle provides code examples illustrating the use of OCCI calls. These programs are provided for demonstration purposes, and are not guaranteed to run on all platforms.
The demonstration programs (demos) are available with your Oracle installation. The location, names, and availability of the programs may vary on different platforms. On a UNIX workstation, the programs are installed in the ORACLE_HOME/rdbms/demo
directory.
The $ORACLE_HOME/rdbms/demo
directory contains not only demos but the file named demo_rdbms.mk
that must be used as a template for building your own OCCI applications or external procedures. Building a new demo_rdbms.mk
file consists of customizing the demo_rdbms.mk
file by adding your own macros to the link line. However, Oracle requires that you keep the macros provided in the demo_rdbms.mk
file, as it will result in simplified maintenance of your own demo_rdbms.mk
files.
When a specific header or SQL file is required by the application, these files are also included. Review the information in the comments at the beginning of the demonstration programs for setups and hints on running the programs.
Prior to running any of these demos, the SQL file occidemo.sql
must be run using the user name and password SCOTT
and TIGER
respectively.
Table A-1 lists the important demonstration programs and the OCCI features that they illustrate.
This section lists each of the OCCI demonstration program files, in addition to the demo make file.
The following code is for the make file that generates the demonstration programs:
# # Example for building demo OCI programs: # # 1. All OCI demos (including extdemo2, extdemo4 and extdemo5): # # make -f demo_rdbms.mk demos # # 2. A single OCI demo: # # make -f demo_rdbms.mk build EXE=demo OBJS="demo.o ..." # e.g. make -f demo_rdbms.mk build EXE=oci02 OBJS=oci02.o # # 3. A single OCI demo with static libraries: # # make -f demo_rdbms.mk build_static EXE=demo OBJS="demo.o ..." # e.g. make -f demo_rdbms.mk build_static EXE=oci02 OBJS=oci02.o # # 4. To regenerate shared library: # # make -f demo_rdbms.mk generate_sharedlib # # 5. All OCCI demos # # make -f demo_rdbms.mk occidemos # # 6. A single OCCI demo: # # make -f demo_rdbms.mk <demoname> # e.g. make -f demo_rdbms.mk occidml # OR # make -f demo_rdbms.mk buildocci EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildocci EXE=occidml OBJS=occidml.o # # 7. A single OCCI demo with static libraries: # # make -f demo_rdbms.mk buildocci_static EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildocci_static EXE=occiblob OBJS=occiblob.o # # 8. All OCI Connection Pooling, Session Pooling and Statement Cache demos # # make -f demo_rdbms.mk cpdemos # # 9. A single OCI Connection Pooling demo: # # make -f demo_rdbms.mk <demoname> # e.g. make -f demo_rdbms.mk ocicp # OR # make -f demo_rdbms.mk buildcp EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildcp EXE=ocicp OBJS=ocicp.o # # 10. A single OCI Connection Pooling demo with static libraries: # # make -f demo_rdbms.mk buildcp_static EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildcp_static EXE=ocicp OBJS=ocicp.o # # 11. A single OCI Session Pooling demo: # # make -f demo_rdbms.mk <demoname> # e.g. make -f demo_rdbms.mk ocisp # OR # make -f demo_rdbms.mk buildcp EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildcp EXE=ocisp OBJS=ocisp.o # # 12. A single OCI Session Pooling demo with static libraries: # # make -f demo_rdbms.mk buildcp_static EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildcp_static EXE=ocisp OBJS=ocisp.o # # 13. A single OCI Statement Cache demo: # # make -f demo_rdbms.mk <demoname> # e.g. make -f demo_rdbms.mk ocisc # OR # make -f demo_rdbms.mk buildcp EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildcp EXE=ocisc OBJS=ocisc.o # # 14. A single OCI Statement Cache demo with static libraries: # # make -f demo_rdbms.mk buildcp_static EXE=demoname OBJS="demoname.o ..." # e.g. make -f demo_rdbms.mk buildcp_static EXE=ocisc OBJS=ocisc.o # # Example for building demo DIRECT PATH API programs: # # 1. All DIRECT PATH API demos: # # make -f demo_rdbms.mk demos_dp # # 2. A single DIRECT PATH API demo: # # make -f demo_rdbms.mk build_dp EXE=demo OBJS="demo.o ..." # e.g. make -f demo_rdbms.mk build_dp EXE=cdemdplp OBJS=cdemdplp.o # # # Example for building external procedures demo programs: # # 1. All external procedure demos: # # 2. A single external procedure demo whose 3GL routines do not use the # "with context" argument: # # make -f demo_rdbms.mk extproc_no_context SHARED_LIBNAME=libname # OBJS="demo.o ..." # e.g. make -f demo_rdbms.mk extproc_no_context SHARED_LIBNAME=epdemo.so # OBJS="epdemo1.o epdemo2.o" # # 3. A single external procedure demo where one or more 3GL routines use the # "with context" argument: # # make -f demo_rdbms.mk extproc_with_context SHARED_LIBNAME=libname # OBJS="demo.o ..." # e.g. make -f demo_rdbms.mk extproc_with_context SHARED_LIBNAME=epdemo.so # OBJS="epdemo1.o epdemo2.o" # e.g. make -f demo_rdbms.mk extproc_with_context # SHARED_LIBNAME=extdemo2.so OBJS="extdemo2.o" # e.g. or For EXTDEMO2 DEMO ONLY: make -f demo_rdbms.mk demos # # 4. To link C++ demos: # # make -f demo_rdbms.mk c++demos # # # NOTE: 1. ORACLE_HOME must be either: # . set in the user's environment # . passed in on the command line # . defined in a modified version of this makefile # # 2. If the target platform support shared libraries (e.g. Solaris) # look in the platform specific documentation for information # about environment variables that need to be properly # defined (e.g. LD_LIBRARY_PATH in Solaris). # include $(ORACLE_HOME)/rdbms/lib/env_rdbms.mk # flag for linking with non-deferred option (default is deferred mode) NONDEFER=false DEMO_DIR=$(ORACLE_HOME)/rdbms/demo DEMO_MAKEFILE = $(DEMO_DIR)/demo_rdbms.mk DEMOS = cdemo1 cdemo2 cdemo3 cdemo4 cdemo5 cdemo81 cdemo82 \ cdemobj cdemolb cdemodsc cdemocor cdemolb2 cdemolbs \ cdemodr1 cdemodr2 cdemodr3 cdemodsa obndra \ cdemoext cdemothr cdemofil cdemofor \ oci02 oci03 oci04 oci05 oci06 oci07 oci08 oci09 oci10 \ oci11 oci12 oci13 oci14 oci15 oci16 oci17 oci18 oci19 oci20 \ oci21 oci22 oci23 oci24 oci25 readpipe cdemosyev \ ociaqdemo00 ociaqdemo01 ociaqdemo02 cdemoucb nchdemo1 DEMOS_DP = cdemdpco cdemdpin cdemdpit cdemdplp cdemdpno cdemdpro cdemdpss C++DEMOS = cdemo6 OCCIDEMOS = occiblob occiclob occicoll occidesc occidml occipool occiproc \ occistre OCCIOTTDEMOS = occiobj occiinh occipobj # OTT Markers Support OCCIOTTDEMOSWITHMARKER = mdemo1 OTTUSR = scott OTTPWD = tiger CPDEMOS = ocicp ocicpproxy ocisp ocisc .SUFFIXES: .o .cob .for .c .pc .cc .cpp demos: $(DEMOS) extdemo2 extdemo4 extdemo5 demos_dp: $(DEMOS_DP) generate_sharedlib: $(SILENT)$(ECHO) "Building client shared library ..." $(SILENT)$(ECHO) "Calling script $$ORACLE_HOME/bin/genclntsh ..." $(GENCLNTSH) $(SILENT)$(ECHO) "The library is $$ORACLE_HOME/lib/libclntsh.so... DONE" BUILD=build $(DEMOS): $(MAKE) -f $(DEMO_MAKEFILE) $(BUILD) EXE=$@ OBJS=$@.o $(DEMOS_DP): cdemodp.c cdemodp0.h cdemodp.h $(MAKE) -f $(DEMO_MAKEFILE) build_dp EXE=$@ OBJS=$@.o c++demos: $(C++DEMOS) $(C++DEMOS): $(MAKE) -f $(DEMO_MAKEFILE) buildc++ EXE=$@ OBJS=$@.o buildc++: $(OBJS) $(MAKECPLPLDEMO) occidemos: $(OCCIDEMOS) $(OCCIOTTDEMOS) $(OCCIOTTDEMOSWITHMARKER) $(OCCIDEMOS): $(MAKE) -f $(DEMO_MAKEFILE) buildocci EXE=$@ OBJS=$@.o $(OCCIOTTDEMOS): $(MAKE) -f $(DEMO_MAKEFILE) ott OTTFILE=$@ $(MAKE) -f $(DEMO_MAKEFILE) buildocci EXE=$@ OBJS="$@.o $@o.o $@m.o" # OTT Markers Support $(OCCIOTTDEMOSWITHMARKER): $(MAKE) -f $(DEMO_MAKEFILE) ott_mrkr OTTFILE=$@ $(MAKE) -f $(DEMO_MAKEFILE) buildocci EXE=$@ OBJS="$@.o $@o.o $@m.o" buildocci: $(OBJS) $(MAKEOCCISHAREDDEMO) buildocci_static: $(OBJS) $(MAKEOCCISTATICDEMO) ott: $(ORACLE_HOME)/bin/ott \ userid=$(OTTUSR)/$(OTTPWD) \ intype=$(OTTFILE).typ \ outtype=$(OTTFILE)out.type \ code=cpp \ hfile=$(OTTFILE).h \ cppfile=$(OTTFILE)o.cpp \ attraccess=private # OTT Markers Suppport ott_mrkr: $(ORACLE_HOME)/bin/ott \ userid=$(OTTUSR)/$(OTTPWD) \ intype=$(OTTFILE).typ \ outtype=$(OTTFILE)out.type \ code=cpp \ hfile=$(OTTFILE).h \ cppfile=$(OTTFILE)o.cpp \ use_marker=true cpdemos: $(CPDEMOS) $(CPDEMOS): $(MAKE) -f $(DEMO_MAKEFILE) buildcp EXE=$@ OBJS=$@.o buildcp: $(OBJS) $(MAKECPSHAREDDEMO) buildcp_static: $(OBJS) $(MAKECPSTATICDEMO) # Pro*C rules # SQL Precompiler macros pc1: $(PCC2C) .pc.c: $(MAKE) -f $(DEMO_MAKEFILE) PCCSRC=$* I_SYM=include= pc1 .pc.o: $(MAKE) -f $(DEMO_MAKEFILE) PCCSRC=$* I_SYM=include= pc1 $(PCCC2O) .cc.o: $(CCC2O) .cpp.o: $(CCC2O) build: $(LIBCLNTSH) $(OBJS) $(BUILDEXE) extdemo2: $(MAKE) -f $(DEMO_MAKEFILE) extproc_with_context SHARED_ LIBNAME=extdemo2.so OBJS="extdemo2.o" extdemo4: $(MAKE) -f $(DEMO_MAKEFILE) extproc_with_context SHARED_ LIBNAME=extdemo4.so OBJS="extdemo4.o" extdemo5: $(MAKE) -f $(DEMO_MAKEFILE) extproc_with_context SHARED_ LIBNAME=extdemo5.so OBJS="extdemo5.o" .c.o: $(C2O) build_dp: $(LIBCLNTSH) $(OBJS) cdemodp.o $(DPTARGET) build_static: $(OBJS) $(O2STATIC) # extproc_no_context and extproc_with_context are the current names of these # targets. The old names, extproc_nocallback and extproc_callback are # preserved for backward compatibility. extproc_no_context extproc_nocallback: $(OBJS) $(BUILDLIB_NO_CONTEXT) extproc_with_context extproc_callback: $(OBJS) $(LIBCLNTSH) $(BUILDLIB_WITH_CONTEXT) clean: $(RM) -f $(DEMOS) $(CPDEMOS) extdemo2 extdemo4 extdemo5 *.o *.so $(RM) -f $(OCCIDEMOS) $(OCCIOTTDEMOS) occi*m.cpp occi*o.cpp occi*.typ occiobj*.h occiinh*.h occipobj*.h $(RM) -f $(OCCIOTTDEMOSWITHMARKER) mdemo*m.cpp mdemo*o.cpp mdemo*.typ mdemo*.h $(RM) -f $(DEMOS_DP)
The following code example demonstrates how to read and write aBLOB:
#include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; /** * The demo sample has starts from startDemo method. This method is called * by main. startDemo calls other methods, the supporting methods for * startDemo are, * insertRows - insert the rows into the table * deleteRows - delete the rows inserted * insertBlob - Inserts a blob and an empty_blob * populateBlob - populates a given blob * dumpBlob - prints the blob as an integer stream */ class demoBlob { private: string username; string password; string url; void insertRows (Connection *conn) throw (SQLException) { Statement *stmt = conn->createStatement ("INSERT INTO print_media(product_ id,ad_id,ad_composite,ad_sourcetext) VALUES (6666,11001,'10001','SHE')"); stmt->executeUpdate(); stmt->setSQL ("INSERT INTO print_media(product_id,ad_id,ad_composite,ad_ sourcetext) VALUES (7777,11001,'1010','HEM')"); stmt->executeUpdate(); conn->commit(); conn->terminateStatement (stmt); } void deleteRows (Connection *conn) throw (SQLException) { Statement *stmt = conn->createStatement ("DELETE print_media WHERE product_ id = 6666 AND ad_id=11001"); stmt->executeUpdate(); stmt->setSQL ("DELETE print_media WHERE product_id = 7777 AND ad_id=11001"); stmt->executeUpdate(); conn->commit(); conn->terminateStatement (stmt); } /** * populating the blob; */ void populateBlob (Blob &blob, int size) throw (SQLException) { Stream *outstream = blob.getStream (1,0); char *buffer = new char[size]; memset (buffer, (char)10, size); outstream->writeBuffer (buffer, size); char *c = (char *)""; outstream->writeLastBuffer (c,0); delete (buffer); blob.closeStream (outstream); } /** * printing the blob data as integer stream */ void dumpBlob (Blob &blob, int size) throw (SQLException) { Stream *instream = blob.getStream (1,0); char *buffer = new char[size]; memset (buffer, NULL, size); instream->readBuffer (buffer, size); cout << "dumping blob: "; for (int i = 0; i < size; ++i) cout << (int) buffer[i]; cout << endl; delete (buffer); blob.closeStream (instream); } /** * public methods */ public: demoBlob () { /** * default values of username & password */ username = "SCOTT"; password = "TIGER"; url = ""; } void setUsername (string u) { username = u; } void setPassword (string p) { password = p; } void setUrl (string u) { url = u; } void runSample () throw (SQLException) { Environment *env = Environment::createEnvironment ( Environment::DEFAULT); try { Connection *conn = env->createConnection (username, password, url); Statement *stmt1; insertRows (conn); /** * Reading a populated blob & printing its property. */ string sqlQuery = "SELECT ad_composite FROM print_media WHERE product_ id=6666"; Statement *stmt = conn->createStatement (sqlQuery); ResultSet *rset = stmt->executeQuery (); while (rset->next ()) { Blob blob = rset->getBlob (1); cout << "Opening the blob in Read only mode" << endl; blob.open (OCCI_LOB_READONLY); int blobLength=blob.length (); cout << "Length of the blob is: " << blobLength << endl; dumpBlob (blob, blobLength); blob.close (); } stmt->closeResultSet (rset); /** * Reading a populated blob & printing its property. */ stmt->setSQL ("SELECT ad_composite FROM print_media WHERE product_id =7777 FOR UPDATE"); rset = stmt->executeQuery (); while (rset->next ()) { Blob blob = rset->getBlob (1); cout << "Opening the blob in read write mode" << endl; blob.open (OCCI_LOB_READWRITE); cout << "Populating the blob" << endl; populateBlob (blob, 20); int blobLength=blob.length (); cout << "Length of the blob is: " << blobLength << endl; dumpBlob (blob, blobLength); blob.close (); } stmt->closeResultSet (rset); deleteRows (conn); conn->terminateStatement (stmt); env->terminateConnection (conn); } catch (SQLException ea) { cout << ea.what(); } Environment::terminateEnvironment (env); } };//end of class demoBlob int main (void) { demoBlob *b = new demoBlob (); b->setUsername ("SCOTT"); b->setPassword ("TIGER"); b->runSample (); }
The following code example demonstrates how to read and write a CLOB:
#include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; /** * The demo sample has starts from startDemo method. This method is called * by main. startDemo calls other methods, the supporting methods for * startDemo are, * insertRows - inserts the rows into the table1 * deleteRows - delete the rows inserted * insertClob - Inserts a clob and an empty_clob * populateClob - populates a given clob * dumpClob - prints the clob as an integer stream */ class demoClob { private: string username; string password; string url; void insertRows (Connection *conn) throw (SQLException) { Statement *stmt = conn->createStatement ("INSERT INTO print_media(product_ id,ad_id,ad_composite,ad_sourcetext) VALUES (3333,11001,'10001','SHE')"); stmt->executeUpdate(); stmt->setSQL ("INSERT INTO print_media(product_id,ad_id,ad_composite,ad_ sourcetext) VALUES (4444,11001,'1010','HEM')"); stmt->executeUpdate(); conn->commit(); conn->terminateStatement (stmt); } void deleteRows (Connection *conn) throw (SQLException) { Statement *stmt = conn->createStatement ("DELETE print_media WHERE product_ id=3333 AND ad_id=11001"); stmt->executeUpdate(); stmt->setSQL("DELETE print_media WHERE product_id=4444 AND ad_id=11001"); stmt->executeUpdate(); conn->commit(); conn->terminateStatement (stmt); } /** * populating the clob; */ void populateClob (Clob &clob, int size) throw (SQLException) { Stream *outstream = clob.getStream (1,0); char *buffer = new char[size]; memset (buffer,'H', size); outstream->writeBuffer (buffer, size); char *c = (char *)""; outstream->writeLastBuffer (c,0); delete (buffer); clob.closeStream (outstream); } /** * printing the clob data as integer stream */ void dumpClob (Clob &clob, int size) throw (SQLException) { Stream *instream = clob.getStream (1,0); char *buffer = new char[size]; memset (buffer, NULL, size); instream->readBuffer (buffer, size); cout << "dumping clob: "; for (int i = 0; i < size; ++i) cout << (char) buffer[i]; cout << endl; delete (buffer); clob.closeStream (instream); } /** * public methods */ public: demoClob () { /** * default values of username & password */ username = "SCOTT"; password = "TIGER"; url = ""; } void setUsername (string u) { username = u; } void setPassword (string p) { password = p; } void setUrl (string u) { url = u; } void runSample () throw (SQLException) { Environment *env = Environment::createEnvironment ( Environment::DEFAULT); try { Connection *conn = env->createConnection (username, password, url); Statement *stmt1; insertRows (conn); /** * Reading a populated clob & printing its property. */ string sqlQuery = "SELECT ad_sourcetext FROM print_media WHERE product_ id=3333"; Statement *stmt = conn->createStatement (sqlQuery); ResultSet *rset = stmt->executeQuery (); while (rset->next ()) { Clob clob = rset->getClob (1); cout << "Opening the clob in Read only mode" << endl; clob.open (OCCI_LOB_READONLY); int clobLength=clob.length (); cout << "Length of the clob is: " << clobLength << endl; dumpClob (clob, clobLength); clob.close (); } stmt->closeResultSet (rset); /** * Reading a populated clob & printing its property. */ stmt->setSQL ("SELECT ad_sourcetext FROM print_media WHERE product_id =4444 FOR UPDATE"); rset = stmt->executeQuery (); while (rset->next ()) { Clob clob = rset->getClob (1); cout << "Opening the clob in read write mode" << endl; clob.open (OCCI_LOB_READWRITE); cout << "Populating the clob" << endl; populateClob (clob, 20); int clobLength=clob.length (); cout << "Length of the clob is: " << clobLength << endl; dumpClob (clob, clobLength); clob.close (); } stmt->closeResultSet (rset); conn->terminateStatement (stmt); deleteRows(conn); env->terminateConnection (conn); } catch (SQLException ea) { cout << ea.what(); } Environment::terminateEnvironment (env); } };//end of class demoClob int main (void) { demoClob *b = new demoClob (); b->setUsername ("SCOTT"); b->setPassword ("TIGER"); b->runSample (); }
The following code example demonstrates how to perform simple insert, delete, and update operations on a table column of type Nested Table
:
/** *occicoll - To exhibit simple insert, delete & update operations" * " on table having a Nested Table column * *Description * Create a program which has insert,delete and update on a * table having a Nested table column. * Perform all these operations using OCCI interface. */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; typedef vector<string> journal; class occicoll { private: Environment *env; Connection *conn; Statement *stmt; string tableName; string typeName; public: occicoll (string user, string passwd, string db) { env = Environment::createEnvironment (Environment::OBJECT); conn = env->createConnection (user, passwd, db); initRows(); } ~occicoll () { env->terminateConnection (conn); Environment::terminateEnvironment (env); } void setTableName (string s) { tableName = s; } void initRows () { try{ Statement *st1 = conn->createStatement ("DELETE FROM journal_tab"); st1->executeUpdate (); st1->setSQL("INSERT INTO journal_tab (jid, jname) VALUES (22, journal ('NATION', 'TIMES'))"); st1->executeUpdate (); st1->setSQL("INSERT INTO journal_tab (jid, jname) VALUES (33, journal ('CRICKET', 'ALIVE'))"); st1->executeUpdate (); conn->commit(); conn->terminateStatement (stmt); }catch(SQLException ex) { cout<<ex.what(); } } /** * Insertion of a row */ void insertRow () { int c1 = 11; journal c2; c2.push_back ("LIFE"); c2.push_back ("TODAY"); c2.push_back ("INVESTOR"); cout << "Inserting row with jid = " << 11 << " and journal_tab (LIFE, TODAY, INVESTOR )" << endl; try{ stmt = conn->createStatement ( "INSERT INTO journal_tab (jid, jname) VALUES (:x, :y)"); stmt->setInt (1, c1); setVector (stmt, 2, c2, "JOURNAL"); stmt->executeUpdate (); }catch(SQLException ex) { cout<<"Exception thrown for insertRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } cout << "Insertion - Successful" << endl; conn->terminateStatement (stmt); } // Displaying all the rows of the table void displayAllRows () { cout << "Displaying all the rows of the table" << endl; stmt = conn->createStatement ( "SELECT jid, jname FROM journal_tab"); journal c2; ResultSet *rs = stmt->executeQuery(); try{ while (rs->next()) { cout << "jid: " << rs->getInt(1) << endl; cout << "jname: "; getVector (rs, 2, c2); for (int i = 0; i < c2.size(); ++i) cout << c2[i] << " "; cout << endl; } }catch(SQLException ex) { cout<<"Exception thrown for displayRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } stmt->closeResultSet (rs); conn->terminateStatement (stmt); } // End of displayAllRows() // Deleting a row in a nested table void deleteRow (int c1, string str) { cout << "Deleting a row in a nested table of strings" << endl; stmt = conn->createStatement ( "SELECT jname FROM journal_tab WHERE jid = :x"); journal c2; stmt->setInt (1, c1); ResultSet *rs = stmt->executeQuery(); try{ if (rs->next()) { getVector (rs, 1, c2); c2.erase (find (c2.begin(), c2.end(), str)); } stmt->setSQL ("UPDATE journal_tab SET jname = :x WHERE jid = :y"); stmt->setInt (2, c1); setVector (stmt, 1, c2, "JOURNAL"); stmt->executeUpdate (); }catch(SQLException ex) { cout<<"Exception thrown for delete row"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } cout << "Deletion - Successful" << endl; conn->commit(); stmt->closeResultSet (rs); conn->terminateStatement (stmt); } // End of deleteRow (int, string) // Updating a row of the nested table of strings void updateRow (int c1, string str) { cout << "Updating a row of the nested table of strings" << endl; stmt = conn->createStatement ( "SELECT jname FROM journal_tab WHERE jid = :x"); journal c2; stmt->setInt (1, c1); ResultSet *rs = stmt->executeQuery(); try{ if (rs->next()) { getVector (rs, 1, c2); c2[0] = str; } stmt->setSQL ("UPDATE journal_tab SET jname = :x WHERE jid = :y"); stmt->setInt (2, c1); setVector (stmt, 1, c2, "JOURNAL"); stmt->executeUpdate (); }catch(SQLException ex) { cout<<"Exception thrown for updateRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } cout << "Updation - Successful" << endl; conn->commit(); stmt->closeResultSet (rs); conn->terminateStatement (stmt); } // End of UpdateRow (int, string) };//end of class occicoll int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; try { cout << "occicoll - Exhibiting simple insert, delete & update operations" " on table having a Nested Table column" << endl; occicoll *demo = new occicoll (user, passwd, db); cout << "Displaying all rows before the operations" << endl; demo->displayAllRows (); demo->insertRow (); demo->deleteRow (11, "TODAY"); demo->updateRow (33, "New_String"); cout << "Displaying all rows after all the operations" << endl; demo->displayAllRows (); delete (demo); cout << "occicoll - done" << endl; }catch (SQLException ea) { cerr << "Error running the demo: " << ea.getMessage () << endl; } }
The following code example demonstrates how to obtain metadata about a table, procedure, and object:
/** * occidesc - Describing the various objects of the database. * * DESCRIPTION : * This program describes the objects of the database, like, table, object * and procedure. * */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; class occidesc { private: Environment *env; Connection *conn; public : /** * Constructor for the occidesc demo program. */ occidesc (string user, string passwd, string db) throw (SQLException) { env = Environment::createEnvironment (Environment::OBJECT); conn = env->createConnection (user, passwd, db); }// end of constructor occidesc (string, string, string ) /** * Destructor for the occidesc demo program. */ ~occidesc () throw (SQLException) { env->terminateConnection (conn); Environment::terminateEnvironment (env); } // end of ~occidesc () // Describing a subtype void describe_type() { cout << "Describing the object - PERSON_OBJ " << endl; MetaData metaData = conn->getMetaData ((char *)"PERSON_OBJ"); int mdTyp = metaData.getInt(MetaData::ATTR_PTYPE); if (mdTyp == MetaData::PTYPE_TYPE) { cout << "PERSON_OBJ is a type" << endl; } int typcode = metaData.getInt(MetaData::ATTR_TYPECODE); if (typcode == OCCI_TYPECODE_OBJECT) cout << "PERSON_OBJ is an object type" << endl; else cout << "PERSON_OBJ is not an object type" << endl; int numtypeattrs = metaData.getInt(MetaData::ATTR_NUM_TYPE_ATTRS); cout << "Object has " << numtypeattrs << " attributes" << endl; try { cout << "Object id: " << metaData.getUInt (MetaData::ATTR_OBJ_ID) << endl; } catch (SQLException ex) { cout << ex.getMessage() << endl; } cout << "Object Name: " << metaData.getString (MetaData::ATTR_OBJ_NAME) << endl; cout << "Schema Name: " << (metaData.getString(MetaData::ATTR_OBJ_SCHEMA)) << endl; cout << "Attribute version: " << (metaData.getString(MetaData::ATTR_VERSION)) << endl; if (metaData.getBoolean(MetaData::ATTR_IS_INCOMPLETE_TYPE)) cout << "Incomplete type" << endl; else cout << "Not Incomplete type" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_SYSTEM_TYPE)) cout << "System type" << endl; else cout << "Not System type" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_PREDEFINED_TYPE)) cout << "Predefined Type" << endl; else cout << "Not Predefined Type" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_TRANSIENT_TYPE)) cout << "Transient Type" << endl; else cout << "Not Transient Type" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_SYSTEM_GENERATED_TYPE)) cout << "System-generated type" << endl; else cout << "Not System-generated type" << endl; if (metaData.getBoolean(MetaData::ATTR_HAS_NESTED_TABLE)) cout << "Has nested table" << endl; else cout << "Does not have nested table" << endl; if (metaData.getBoolean(MetaData::ATTR_HAS_LOB)) cout << "Has LOB" << endl; else cout << "Does not have LOB" << endl; if (metaData.getBoolean(MetaData::ATTR_HAS_FILE)) cout << "Has BFILE" << endl; else cout << "Does not have BFILE" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_INVOKER_RIGHTS)) cout << "Object is Invoker rights" << endl; else cout << "Object is Not Invoker rights" << endl; RefAny ref = metaData.getRef (MetaData::ATTR_REF_TDO); MetaData md1 = conn->getMetaData (ref); vector<MetaData> v1 = md1.getVector (MetaData::ATTR_LIST_TYPE_ATTRS); for (int i = 0; i < v1.size (); ++i) { MetaData md2 = (MetaData)v1[i]; cout << "Column Name :" << (md2.getString(MetaData::ATTR_NAME)) << endl; cout << " Data Type :" << (printType (md2.getInt(MetaData::ATTR_DATA_TYPE))) << endl; cout << " Size :" << md2.getInt(MetaData::ATTR_DATA_SIZE) << endl; cout << " Precision :" << md2.getInt(MetaData::ATTR_PRECISION) << endl; cout << " Scale :" << md2.getInt(MetaData::ATTR_SCALE) << endl << endl; } cout << "describe_type - done" << endl; } // end of describe_type() // Describing a table void describe_table () { cout << "Describing the table - AUTHOR_TAB" << endl; vector<MetaData> v1; MetaData metaData = conn->getMetaData("AUTHOR_TAB"); cout << "Object name:" << (metaData.getString(MetaData::ATTR_OBJ_NAME)) << endl; cout << "Schema:" << (metaData.getString(MetaData::ATTR_OBJ_SCHEMA)) << endl; if (metaData.getInt(MetaData::ATTR_PTYPE) == MetaData::PTYPE_TABLE) { cout << "AUTHOR_TAB is a table" << endl; } else cout << "AUTHOR_TAB is not a table" << endl; if (metaData.getBoolean(MetaData::ATTR_PARTITIONED)) cout << "Table is partitioned" << endl; else cout << "Table is not partitioned" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_TEMPORARY)) cout << "Table is temporary" << endl; else cout << "Table is not temporary" << endl; if (metaData.getBoolean(MetaData::ATTR_IS_TYPED)) cout << "Table is typed" << endl; else cout << "Table is not typed" << endl; if (metaData.getBoolean(MetaData::ATTR_CLUSTERED)) cout << "Table is clustered" << endl; else cout << "Table is not clustered" << endl; if (metaData.getBoolean(MetaData::ATTR_INDEX_ONLY)) cout << "Table is Index-only" << endl; else cout << "Table is not Index-only" << endl; cout << "Duration:"; switch (metaData.getInt(MetaData::ATTR_DURATION)) { case MetaData::DURATION_SESSION : cout << "Connection" << endl; break; case MetaData::DURATION_TRANS : cout << "Transaction" << endl; break; case MetaData::DURATION_NULL : cout << "Table not temporary" << endl; break; } try { cout << "Data Block Address:" << metaData.getUInt (MetaData::ATTR_RDBA) << endl; } catch (SQLException ex) { cout << ex.getMessage() << endl; } try { cout << "Tablespace:" << metaData.getInt (MetaData::ATTR_TABLESPACE) << endl; } catch (SQLException ex) { cout << ex.getMessage() << endl; } try { cout << "Object Id:" << metaData.getUInt(MetaData::ATTR_OBJID) << endl; } catch (SQLException ex) { cout << ex.getMessage() << endl; } int columnCount = metaData.getInt(MetaData::ATTR_NUM_COLS); cout << "Number of Columns : " << columnCount << endl; v1 = metaData.getVector(MetaData::ATTR_LIST_COLUMNS); for(int i=0; i < v1.size(); i++) { MetaData md = v1[i]; cout << " Column Name :" << (md.getString(MetaData::ATTR_NAME)) << endl; cout << " Data Type :" << (printType (md.getInt(MetaData::ATTR_DATA_TYPE))) << endl; cout << " Size :" << md.getInt(MetaData::ATTR_DATA_SIZE) << endl; cout << " Precision :" << md.getInt(MetaData::ATTR_PRECISION) << endl; cout << " Scale :" << md.getInt(MetaData::ATTR_SCALE) << endl; bool isnull = md.getBoolean(MetaData::ATTR_IS_NULL); if (isnull) cout << " Allows null" << endl; else cout << " Does not allow null" << endl; } cout << "describe_table - done" << endl; } // end of describe_table () // Describing a procedure void describe_proc () { cout << "Describing the procedure - DEMO_PROC" << endl; MetaData metaData = conn->getMetaData("DEMO_PROC"); vector<MetaData> v1 = metaData.getVector ( MetaData::ATTR_LIST_ARGUMENTS ); cout << "The number of arguments are:" << v1.size() << endl; cout << "Object Name :" << (metaData.getString(MetaData::ATTR_OBJ_NAME)) << endl; cout << "Schema Name :" << (metaData.getString(MetaData::ATTR_OBJ_SCHEMA)) << endl; if (metaData.getInt(MetaData::ATTR_PTYPE) == MetaData:: PTYPE_PROC) { cout << "DEMO_PROC is a procedure" << endl; } else { if (metaData.getInt(MetaData::ATTR_PTYPE) == MetaData:: PTYPE_FUNC) { cout << "DEMO_PROC is a function" << endl; } } try { cout << "Object Id:" << metaData.getUInt(MetaData::ATTR_OBJ_ID) << endl; } catch (SQLException ex) { cout << ex.getMessage() << endl; } try { cout << "Name :" << (metaData.getString(MetaData::ATTR_NAME)) << endl; } catch (SQLException ex) { cout << ex.getMessage() << endl; } if (metaData.getBoolean(MetaData::ATTR_IS_INVOKER_RIGHTS)) cout << "It is Invoker-rights" << endl; else cout << "It is not Invoker-rights" << endl; cout << "Overload Id:" << metaData.getInt(MetaData::ATTR_OVERLOAD_ID) << endl; for(int i=0; i < v1.size(); i++) { MetaData md = v1[i]; cout << "Column Name :" << (md.getString(MetaData::ATTR_NAME)) << endl; cout << "DataType :" << (printType (md.getInt(MetaData::ATTR_DATA_TYPE))) << endl; cout << "Argument Mode:"; int mode = md.getInt (MetaData::ATTR_IOMODE); if (mode == 0) cout << "IN" << endl; if (mode == 1) cout << "OUT" << endl; if (mode == 2) cout << "IN/OUT" << endl; cout << "Size :" << md.getInt(MetaData::ATTR_DATA_SIZE) << endl; cout << "Precision :" << md.getInt(MetaData::ATTR_PRECISION) << endl; cout << "Scale :" << md.getInt(MetaData::ATTR_SCALE) << endl; int isNull = md.getInt ( MetaData::ATTR_IS_NULL); if (isNull != 0) cout << "Allows null," << endl; else cout << "Does not allow null," << endl; int hasDef = md.getInt ( MetaData::ATTR_HAS_DEFAULT); if (hasDef != 0) cout << "Has Default" << endl; else cout << "Does not have Default" << endl; } cout << "test1 - done" << endl; } // Method which prints the data type string printType (int type) { switch (type) { case OCCI_SQLT_CHR : return "VARCHAR2"; break; case OCCI_SQLT_NUM : return "NUMBER"; break; case OCCIINT : return "INTEGER"; break; case OCCIFLOAT : return "FLOAT"; break; case OCCI_SQLT_STR : return "STRING"; break; case OCCI_SQLT_VNU : return "VARNUM"; break; case OCCI_SQLT_LNG : return "LONG"; break; case OCCI_SQLT_VCS : return "VARCHAR"; break; case OCCI_SQLT_RID : return "ROWID"; break; case OCCI_SQLT_DAT : return "DATE"; break; case OCCI_SQLT_VBI : return "VARRAW"; break; case OCCI_SQLT_BIN : return "RAW"; break; case OCCI_SQLT_LBI : return "LONG RAW"; break; case OCCIUNSIGNED_INT : return "UNSIGNED INT"; break; case OCCI_SQLT_LVC : return "LONG VARCHAR"; break; case OCCI_SQLT_LVB : return "LONG VARRAW"; break; case OCCI_SQLT_AFC : return "CHAR"; break; case OCCI_SQLT_AVC : return "CHARZ"; break; case OCCI_SQLT_RDD : return "ROWID"; break; case OCCI_SQLT_NTY : return "NAMED DATA TYPE"; break; case OCCI_SQLT_REF : return "REF"; break; case OCCI_SQLT_CLOB: return "CLOB"; break; case OCCI_SQLT_BLOB: return "BLOB"; break; case OCCI_SQLT_FILE: return "BFILE"; break; } } // End of printType (int) }; // end of class occidesc int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; cout << "occidesc - Describing the various objects of the database" << endl; occidesc *demo = new occidesc (user, passwd, db); demo->describe_table(); demo->describe_type(); demo->describe_proc(); delete demo; }// end of main ()
The following code example demonstrates how to perform insert, select, update, and delete operations of a table row by using OCCI:
/** * occidml - To exhibit the insertion, Selection, updating and deletion of * a row through OCCI. * * Description * Create a program which has insert, select, update & delete as operations. * Perform all these operations using OCCI interface. */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; class occidml { private: Environment *env; Connection *conn; Statement *stmt; public: occidml (string user, string passwd, string db) { env = Environment::createEnvironment (Environment::DEFAULT); conn = env->createConnection (user, passwd, db); } ~occidml () { env->terminateConnection (conn); Environment::terminateEnvironment (env); } /** * Insertion of a row with dynamic binding, PreparedStatement functionality. */ void insertBind (int c1, string c2) { string sqlStmt = "INSERT INTO author_tab VALUES (:x, :y)"; stmt=conn->createStatement (sqlStmt); try{ stmt->setInt (1, c1); stmt->setString (2, c2); stmt->executeUpdate (); cout << "insert - Success" << endl; }catch(SQLException ex) { cout<<"Exception thrown for insertBind"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } conn->terminateStatement (stmt); } /** * Inserting a row into the table. */ void insertRow () { string sqlStmt = "INSERT INTO author_tab VALUES (111, 'ASHOK')"; stmt = conn->createStatement (sqlStmt); try{ stmt->executeUpdate (); cout << "insert - Success" << endl; }catch(SQLException ex) { cout<<"Exception thrown for insertRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } conn->terminateStatement (stmt); } /** * updating a row */ void updateRow (int c1, string c2) { string sqlStmt = "UPDATE author_tab SET author_name = :x WHERE author_id = :y"; stmt = conn->createStatement (sqlStmt); try{ stmt->setString (1, c2); stmt->setInt (2, c1); stmt->executeUpdate (); cout << "update - Success" << endl; }catch(SQLException ex) { cout<<"Exception thrown for updateRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } conn->terminateStatement (stmt); } /** * deletion of a row */ void deleteRow (int c1, string c2) { string sqlStmt = "DELETE FROM author_tab WHERE author_id= :x AND author_name = :y"; stmt = conn->createStatement (sqlStmt); try{ stmt->setInt (1, c1); stmt->setString (2, c2); stmt->executeUpdate (); cout << "delete - Success" << endl; }catch(SQLException ex) { cout<<"Exception thrown for deleteRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } conn->terminateStatement (stmt); } /** * displaying all the rows in the table */ void displayAllRows () { string sqlStmt = "SELECT author_id, author_name FROM author_tab"; stmt = conn->createStatement (sqlStmt); ResultSet *rset = stmt->executeQuery (); try{ while (rset->next ()) { cout << "author_id: " << rset->getInt (1) << " author_name: " << rset->getString (2) << endl; } }catch(SQLException ex) { cout<<"Exception thrown for displayAllRows"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } stmt->closeResultSet (rset); conn->terminateStatement (stmt); } }; // end of class occidml int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; cout << "occidml - Exhibiting simple insert, delete & update operations" << endl; occidml *demo = new occidml (user, passwd, db); cout << "Displaying all records before any operation" << endl; demo->displayAllRows (); cout << "Inserting a record into the table author_tab " << endl; demo->insertRow (); cout << "Displaying the records after insert " << endl; demo->displayAllRows (); cout << "Inserting a records into the table author_tab using dynamic bind" << endl; demo->insertBind (222, "ANAND"); cout << "Displaying the records after insert using dynamic bind" << endl; demo->displayAllRows (); cout << "deleting a row with author_id as 222 from author_tab table" << endl; demo->deleteRow (222, "ANAND"); cout << "updating a row with author_id as 444 from author_tab table" << endl; demo->updateRow (444, "ADAM"); cout << "displaying all rows after all the operations" << endl; demo->displayAllRows (); delete (demo); cout << "occidml - done" << endl; }
CASE=LOWER MAPFILE=occiinhm.cpp TYPE FOREIGN_STUDENT as foreign_student
The following code example demonstrates object inheritance by using insert, select, update, and delete operations on a table row of subtype table:
/** * occiinh.cpp - To exhibit the insertion, selection, updating and deletion * of a row of a table of derived object. * * Description * Create a program which has insert, select, update & delete as operations * of a object. Perform all these operations using OCCI interface. * Hierarchy * person_typ <---- student <----- parttime_stud <----- foreign_student **/ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; #include "occiinhm.h" /* Add on your methods in this class*/ class foreign_student_obj : public foreign_student { /* New methods can be added here */ }; class occiinh { private: Environment *env; Connection *con; // This method will return the Ref RefAny getRefObj(string sqlString) { Statement *stmt = con->createStatement (sqlString); ResultSet *rs; try { rs = stmt->executeQuery (); if ( rs->next() ) { RefAny ref1 = rs->getRef (1); stmt->closeResultSet (rs); con->terminateStatement (stmt); return ref1; } } catch(SQLException ex) { cout << "Error in fetching ref" << endl; } stmt->closeResultSet (rs); con->terminateStatement (stmt); } public: occiinh (string user, string passwd, string db) throw (SQLException) { env = Environment::createEnvironment (Environment::OBJECT); occiinhm(env); con = env->createConnection (user, passwd, db); }// end of constructor occiinh (string, string, string) ~occiinh () throw (SQLException) { env->terminateConnection (con); Environment::terminateEnvironment (env); }// end of destructor /** * Insertion of a row */ void insertRow () throw (SQLException) { cout << "Inserting a record (joe)" << endl; string sqlStmt = "INSERT INTO foreign_student_tab VALUES(:a)"; Statement *stmt = con->createStatement (sqlStmt); string fs_name = "joe"; Number fs_ssn (4); Date fs_dob(env, 2000, 5, 11, 16, 05, 0); Number fs_stud_id (400); Ref< person_typ > fs_teammate = getRefObj( "SELECT REF(a) FROM person_tab a where name='john'"); Number fs_course_id(4000); Ref< student > fs_partner = getRefObj( "SELECT REF(a) FROM student_tab a"); string fs_country = "india"; Ref< parttime_stud > fs_leader = getRefObj( "SELECT REF(a) FROM parttime_stud_tab a"); foreign_student_obj fsobj; foreign_student_obj *fs_obj=&fsobj; fs_obj->setname(fs_name); fs_obj->setssn(fs_ssn); fs_obj->setdob(fs_dob); fs_obj->setstud_id(fs_stud_id); fs_obj->setteammate(fs_teammate); fs_obj->setcourse_id(fs_course_id); fs_obj->setpartner(fs_partner); fs_obj->setcountry(fs_country); fs_obj->setleader(fs_leader); stmt->setObject(1, fs_obj); stmt->executeUpdate(); con->terminateStatement (stmt); cout << "Insertion Successful" << endl; }// end of insertRow (); /** * updating a row */ void updateRow () throw (SQLException) { cout << "Upadating record (Changing name,teammate and course_id)" << endl; string sqlStmt = "UPDATE foreign_student_tab SET name=:x, teammate=:y, course_id=:z"; Statement *stmt = con->createStatement (sqlStmt); string fs_name = "jeffree"; Ref< person_typ > fs_teammate = getRefObj( "SELECT REF(a) FROM person_tab a where name='jill'"); Number fs_course_id(5000); stmt->setString(1, fs_name); stmt->setRef(2,fs_teammate); stmt->setInt(3, fs_course_id); stmt->executeUpdate (); con->commit(); con->terminateStatement (stmt); cout << "Updation Successful" << endl; }// end of updateRow (int, string); /** * deletion of a row */ void deleteRow () throw (SQLException) { cout << "Deletion of jeffree record " << endl; string sqlStmt = "DELETE FROM foreign_student_tab where name=:x"; Statement *stmt = con->createStatement (sqlStmt); string fs_name = "jeffree"; stmt->setString(1,fs_name); stmt->executeUpdate(); con->commit(); con->terminateStatement (stmt); cout << "Deletion Successful" << endl; }// end of deleteRow (int, string); /** * displaying all the rows in the table */ void displayAllRows () throw (SQLException) { int count=0; string sqlStmt = "SELECT REF(a) FROM foreign_student_tab a"; Statement *stmt = con->createStatement (sqlStmt); ResultSet *resultSet = stmt->executeQuery (); while (resultSet->next ()) { count++; RefAny fs_refany = resultSet->getRef(1); Ref <foreign_student_obj> fs_ref(fs_refany); fs_ref.setPrefetch(4); string fmt = "DD-MON-YYYY"; string nlsParam = "NLS_DATE_LANGUAGE = American"; Date fs_dob = fs_ref->getdob(); string date1 = fs_dob.toText (fmt, nlsParam); cout << "Foreign Student Information" << endl; cout << "Name : " << fs_ref->getname(); cout << " SSN : " << (int)fs_ref->getssn(); cout << " DOB : " << date1 << endl; cout << "Stud id : " << (int)fs_ref->getstud_id() ; cout << " Course id : " << (int)fs_ref->getcourse_id(); cout << " Country : " << fs_ref->getcountry() <<endl; Ref <person_typ> fs_teammate = (Ref <person_typ>) fs_ref->getteammate(); cout << "Teammate's Information " << endl; cout << "Name : " << fs_teammate->getname(); cout << " SSN : " << (int)fs_teammate->getssn(); fs_dob = fs_teammate->getdob(); date1 = fs_dob.toText(fmt, nlsParam); cout << " DOB : " << date1 << endl << endl; /* Leader */ Ref< parttime_stud > fs_leader = (Ref < parttime_stud >) fs_ref->getleader(); /* Leader's Partner */ Ref < student > fs_partner = (Ref <student> ) fs_leader->getpartner(); /* Leader's Partenr's teammate */ fs_teammate = (Ref <person_typ>) fs_partner->getteammate(); cout << "Leader Information " << endl; cout << "Name : " << fs_leader->getname(); cout << " SSN : " << (int)fs_leader->getssn(); fs_dob = fs_leader->getdob(); date1 = fs_dob.toText(fmt, nlsParam); cout << " DOB : " << date1 << endl; cout << "Stud id : " << (int)fs_leader->getstud_id(); cout << " Course id : " << (int)fs_leader->getcourse_id() << endl; cout << "Leader's Partner's Information " << endl; cout << "Name : " << fs_partner->getname() ; cout << " SSN : " << (int)fs_partner->getssn(); fs_dob = fs_partner->getdob(); date1 = fs_dob.toText(fmt, nlsParam); cout << " DOB : " << date1 ; cout << " Stud id : " << (int)fs_partner->getstud_id() << endl; cout << "Leader's Partner's Teammate's Information " << endl; cout << "Name : " << fs_teammate->getname(); cout << " SSN : " << (int)fs_teammate->getssn(); fs_dob = fs_teammate->getdob(); date1 = fs_dob.toText(fmt, nlsParam); cout << " DOB : " << date1 << endl << endl; }//end of while (resultSet->next ()); if (count <=0) cout << "No record found " << endl; stmt->closeResultSet (resultSet); con->terminateStatement (stmt); }// end of updateRow (string); }; // end of class occiinh int main (void) { string user = "scott"; string passwd = "tiger"; string db = ""; try { cout << "occiinh - Exhibiting simple insert, delete & update operations" " on Oracle objects" << endl; occiinh *demo = new occiinh (user, passwd, db); cout << "displaying all rows before operations" << endl; demo->displayAllRows (); demo->insertRow (); cout << "displaying all rows after insertions" << endl; demo->displayAllRows (); demo->updateRow (); cout << "displaying all rows after updations" << endl; demo->displayAllRows (); demo->deleteRow (); cout << "displaying all rows after deletions" << endl; demo->displayAllRows (); delete (demo); cout << "occiinh - done" << endl; }catch (SQLException ea) { cerr << "Error running the demo: " << ea.getMessage () << endl; } }// end of int main (void);
CASE=SAME MAPFILE=occiobjm.cpp TYPE address as address
The following code example demonstrates how to perform insert, select, update, and delete operations on a table row containing an object as one of its columns:
/** * occiobj.cpp - To exhibit the insertion, selection, updating and deletion * of a row containing object as one of the column. * * Description * Create a program which has insert, select, update & delete as operations * of a object. Perform all these operations using OCCI interface. */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; #include "occiobjm.h" class occiobj { private: Environment *env; Connection *con; Statement *stmt; public: occiobj (string user, string passwd, string db) { env = Environment::createEnvironment (Environment::OBJECT); occiobjm (env); con = env->createConnection (user, passwd, db); } ~occiobj () { env->terminateConnection (con); Environment::terminateEnvironment (env); } /** * Insertion of a row */ void insertRow (int c1, int a1, string a2) { cout << "Inserting record - Publisher id :" << c1 << ", Publisher address :" << a1 << ", " << a2 <<endl; string sqlStmt = "INSERT INTO publisher_tab VALUES (:x, :y)"; try{ stmt = con->createStatement (sqlStmt); stmt->setInt (1, c1); address *o = new address (); o->setStreet_no (Number ( a1)); o->setCity (a2); stmt->setObject (2, o); stmt->executeUpdate (); cout << "Insert - Success" << endl; delete (o); }catch(SQLException ex) { cout<<"Exception thrown for insertRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } con->terminateStatement (stmt); } /** * updating a row */ void updateRow (int c1, int a1, string a2) { cout << "Upadating record with publisher id :"<< c1 << endl; string sqlStmt = "UPDATE publisher_tab SET publisher_add= :x WHERE publisher_id = :y"; try{ stmt = con->createStatement (sqlStmt); address *o = new address (); o->setStreet_no (Number ( a1)); o->setCity (a2); stmt->setObject (1, o); stmt->setInt (2, c1); stmt->executeUpdate (); cout << "Update - Success" << endl; delete (o); }catch(SQLException ex) { cout<<"Exception thrown for updateRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } con->terminateStatement (stmt); } /** * deletion of a row */ void deleteRow (int c1, int a1, string a2) { cout << "Deletion of record where publisher id :" << c1 <<endl; string sqlStmt = "DELETE FROM publisher_tab WHERE publisher_id= :x AND publisher_add = :y"; try{ stmt = con->createStatement (sqlStmt); stmt->setInt (1, c1); address *o = new address (); o->setStreet_no (Number ( a1)); o->setCity (a2); stmt->setObject (2, o); stmt->executeUpdate (); cout << "Delete - Success" << endl; delete (o); }catch(SQLException ex) { cout<<"Exception thrown for deleteRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } con->terminateStatement (stmt); } /** * displaying all the rows in the table */ void displayAllRows () { string sqlStmt = "SELECT publisher_id, publisher_add FROM publisher_tab"; try{ stmt = con->createStatement (sqlStmt); ResultSet *rset = stmt->executeQuery (); while (rset->next ()) { cout << "publisher id: " << rset->getInt (1) << " publisher address: address (" ; address *o = (address *)rset->getObject (2); cout << (int)o->getStreet_no () << ", " << o->getCity () << ")" << endl; } stmt->closeResultSet (rset); }catch(SQLException ex) { cout<<"Exception thrown for displayAllRows"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } con->terminateStatement (stmt); } };//end of class occiobj; int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; try { cout << "occiobj - Exhibiting simple insert, delete & update operations" " on Oracle objects" << endl; occiobj *demo = new occiobj (user, passwd, db); cout << "displaying all rows before operations" << endl; demo->displayAllRows (); demo->insertRow (12, 122, "MIKE"); demo->deleteRow (11, 121, "ANNA"); demo->updateRow (23, 123, "KNUTH"); cout << "displaying all rows after all operations" << endl; demo->displayAllRows (); delete (demo); cout << "occiobj - done" << endl; }catch (SQLException ea) { cerr << "Error running the demo: " << ea.getMessage () << endl; } }
CASE=SAME MAPFILE=occipobjm.cpp TYPE address as address
The following code example demonstrates how to perform insert, select, and update operations on persistent objects, as well as how to pin, unpin, mark for deletion, and flush a persistent object:
/** * occipobj.cpp - Manipulation (Insertion, selection & updating) of * persistant objects, along with pinning, unpinning, marking * for deletion & flushing. * * Description * Create a program which has insert, select, update & delete as operations * of a persistant object. Along with the these the operations on Ref. are * pinning, unpinning, marked for deletion & flushing. * */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; #include "occipobjm.h" class address_obj : public address { public: address_obj() { } address_obj(Number sno,string cty) { setStreet_no(sno); setCity(cty); } }; class occipobj { private: Environment *env; Connection *conn; Statement *stmt; string tableName; string typeName; public: occipobj (string user, string passwd, string db) { env = Environment::createEnvironment (Environment::OBJECT); occipobjm (env); conn = env->createConnection (user, passwd, db); } ~occipobj () { env->terminateConnection (conn); Environment::terminateEnvironment (env); } void setTableName (string s) { tableName = s; } /** * Insertion of a row */ void insertRow (int a1, string a2) { cout << "Inserting row ADDRESS (" << a1 << ", " << a2 << ")" << endl; Number n1(a1); address_obj *o = new (conn, tableName) address_obj(n1, a2); conn->commit (); cout << "Insertion - Successful" << endl; } /** * updating a row */ void updateRow (int b1, int a1, string a2) { cout << "Updating a row with attribute a1 = " << b1 << endl; stmt = conn->createStatement ("SELECT REF(a) FROM address_tab a WHERE street_no = :x FOR UPDATE"); stmt->setInt (1, b1); ResultSet *rs = stmt->executeQuery (); try{ if ( rs->next() ) { RefAny rany = rs->getRef (1); Ref <address_obj > r1(rany); address_obj *o = r1.ptr(); o->markModified (); o->setStreet_no (Number (a1)); o->setCity (a2); o->flush (); } }catch(SQLException ex) { cout<<"Exception thrown updateRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } conn->commit (); conn->terminateStatement (stmt); cout << "Updation - Successful" << endl; } /** * deletion of a row */ void deleteRow (int a1, string a2) { cout << "Deleting a row with object ADDRESS (" << a1 << ", " << a2 << ")" << endl; stmt = conn->createStatement ("SELECT REF(a) FROM address_tab a WHERE street_no = :x AND city = :y FOR UPDATE"); stmt->setInt (1, a1); stmt->setString (2, a2); ResultSet *rs = stmt->executeQuery (); try{ if ( rs->next() ) { RefAny rany = rs->getRef (1); Ref<address_obj > r1(rany); address_obj *o = r1.ptr(); o->markDelete (); } }catch(SQLException ex) { cout<<"Exception thrown for deleteRow"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } conn->commit (); conn->terminateStatement (stmt); cout << "Deletion - Successful" << endl; } /** * displaying all the rows in the table */ void displayAllRows () { string sqlStmt = "SELECT REF (a) FROM address_tab a"; stmt = conn->createStatement (sqlStmt); ResultSet *rset = stmt->executeQuery (); try{ while (rset->next ()) { RefAny rany = rset->getRef (1); Ref<address_obj > r1(rany); address_obj *o = r1.ptr(); cout << "ADDRESS(" << (int)o->getStreet_no () << ", " << o->getCity () << ")" << endl; } }catch(SQLException ex) { cout<<"Exception thrown for displayAllRows"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } stmt->closeResultSet (rset); conn->terminateStatement (stmt); } }; // end of class occipobj int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; try { cout << "occipobj - Exhibiting simple insert, delete & update operations" " on persistent objects" << endl; occipobj *demo = new occipobj (user, passwd, db); cout << "Displaying all rows before the opeations" << endl; demo->displayAllRows (); demo->setTableName ("ADDRESS_TAB"); demo->insertRow (21, "KRISHNA"); demo->deleteRow (22, "BOSTON"); demo->updateRow (33, 123, "BHUMI"); cout << "Displaying all rows after all the operations" << endl; demo->displayAllRows (); delete (demo); cout << "occipobj - done" << endl; }catch (SQLException ea) { cerr << "Error running the demo: " << ea.getMessage () << endl; } }
The following code example demonstrates how to use the connection pool interface of OCCI:
/** * occipool - Demontrating the Connection Pool interface of OCCI. * * DESCRIPTION : * This program demonstates the creating and using of connection pool in the * database and fetching records of a table. * */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; class occipool { private: Environment *env; Connection *con; Statement *stmt; public : /** * Constructor for the occipool test case. */ occipool () { env = Environment::createEnvironment (Environment::DEFAULT); }// end of constructor occipool () /** * Destructor for the occipool test case. */ ~occipool () { Environment::terminateEnvironment (env); } // end of ~occipool () /** * The testing logic of the test case. */ dvoid select () { cout << "occipool - Selecting records using ConnectionPool interface" << endl; const string poolUserName = "SCOTT"; const string poolPassword = "TIGER"; const string connectString = ""; const string username = "SCOTT"; const string passWord = "TIGER"; unsigned int maxConn = 5; unsigned int minConn = 3; unsigned int incrConn = 2; ConnectionPool *connPool = env->createConnectionPool (poolUserName, poolPassword, connectString, minConn, maxConn, incrConn); try{ if (connPool) cout << "SUCCESS - createConnectionPool" << endl; else cout << "FAILURE - createConnectionPool" << endl; con = connPool->createConnection (username, passWord); if (con) cout << "SUCCESS - createConnection" << endl; else cout << "FAILURE - createConnection" << endl; }catch(SQLException ex) { cout<<"Exception thrown for createConnectionPool"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } cout << "retrieving the data" << endl; stmt = con->createStatement ("SELECT author_id, author_name FROM author_tab"); ResultSet *rset = stmt->executeQuery(); while (rset->next()) { cout << "author_id:" << rset->getInt (1) << endl; cout << "author_name:" << rset->getString (2) << endl; } stmt->closeResultSet (rset); con->terminateStatement (stmt); connPool->terminateConnection (con); env->terminateConnectionPool (connPool); cout << "occipool - done" << endl; } // end of test (Connection *) }; // end of class occipool int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; occipool *demo = new occipool (); demo->select(); delete demo; }// end of main ()
The following code example demonstrates how to invoke PL/SQL procedures with bind parameters:
/** * occiproc - Demonstrating the invoking of a PL/SQL function and procedure * using OCCI. * * DESCRIPTION : * This program demonstrates the invoking a PL/SQL function and procedure * having IN, IN/OUT and OUT parameters. * */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; class occiproc { private: Environment *env; Connection *con; public : /** * Constructor for the occiproc demo program. */ occiproc (string user, string passwd, string db) throw (SQLException) { env = Environment::createEnvironment (Environment::DEFAULT); con = env->createConnection (user, passwd, db); }// end of constructor occiproc (string, string, string ) /** * Destructor for the occiproc demo program. */ ~occiproc () throw (SQLException) { env->terminateConnection (con); Environment::terminateEnvironment (env); } // end of ~occiproc () // Function to call a PL/SQL procedure void callproc () { cout << "callproc - invoking a PL/SQL procedure having IN, OUT and IN/OUT "; cout << "parameters" << endl; Statement *stmt = con->createStatement ("BEGIN demo_proc(:v1, :v2, :v3); END;"); cout << "Executing the block :" << stmt->getSQL() << endl; stmt->setInt (1, 10); stmt->setString (2, "IN"); stmt->registerOutParam (2, OCCISTRING, 30, ""); stmt->registerOutParam (3, OCCISTRING, 30, ""); int updateCount = stmt->executeUpdate (); cout << "Update Count:" << updateCount << endl; string c1 = stmt->getString (2); string c2 = stmt->getString (3); cout << "Printing the INOUT & OUT parameters:" << endl; cout << "Col2:" << c1 << " Col3:" << c2 << endl; con->terminateStatement (stmt); cout << "occiproc - done" << endl; } // end of callproc () // Function to call a PL/SQL function void callfun () { cout << "callfun - invoking a PL/SQL function having IN, OUT and IN/OUT "; cout << "parameters" << endl; Statement *stmt = con->createStatement ("BEGIN :a := demo_fun(:v1, :v2, :v3); END;"); cout << "Executing the block :" << stmt->getSQL() << endl; stmt->setInt (2, 10); stmt->setString (3, "IN"); stmt->registerOutParam (1, OCCISTRING, 30, ""); stmt->registerOutParam (3, OCCISTRING, 30, ""); stmt->registerOutParam (4, OCCISTRING, 30, ""); int updateCount = stmt->executeUpdate (); cout << "Update Count : " << updateCount << endl; string c1 = stmt->getString (1); string c2 = stmt->getString (3); string c3 = stmt->getString (4); cout << "Printing the INOUT & OUT parameters :" << endl; cout << "Col2:" << c2 << " Col3:" << c3 << endl; cout << "Printing the return value of the function :"; cout << c1 << endl; con->terminateStatement (stmt); cout << "occifun - done" << endl; } // end of callfun () }; // end of class occiproc int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; cout << "occiproc - invoking a PL/SQL function and procedure having "; cout << "parameters" << endl; occiproc *demo = new occiproc (user, passwd, db); demo->callproc(); demo->callfun(); delete demo; }// end of main ()
The following code example demonstrates how to use OCCI ResultSet
streams:
/** * occistrm - Demonstrating the usage of streams for VARCHAR2 data * * Description * This demo program selects VARCHAR2 data using stream operations. */ #include <iostream.h> #include <occi.h> using namespace oracle::occi; using namespace std; class occistrm { private: Environment *env; Connection *conn; public: occistrm (string user, string passwd, string db) throw (SQLException) { env = Environment::createEnvironment (Environment::DEFAULT); conn = env->createConnection (user, passwd, db); }// end of constructor occistrm (string, string, string) ~occistrm () throw (SQLException) { env->terminateConnection (conn); Environment::terminateEnvironment (env); }// end of destructor /** * displaying all the rows in the table */ void displayAllRows () { Statement *stmt = conn->createStatement ( "SELECT summary FROM book WHERE bookid = 11"); stmt->execute (); ResultSet *rs = stmt->getResultSet (); rs->setCharacterStreamMode(1, 4000); char buffer[500]; int length = 0; unsigned int size = 500; while (rs->next ()) { Stream *stream = rs->getStream (1); while( (length=stream->readBuffer(buffer, size))!=-1) { cout << "Read " << length << " bytes from stream" << endl; } } stmt->closeResultSet (rs); conn->terminateStatement (stmt); }// end of updateRow (string); }; // end of class occistrm int main (void) { string user = "SCOTT"; string passwd = "TIGER"; string db = ""; cout << "occistrm - Exhibiting usage of streams for VARCHAR2 data" << endl; occistrm *demo = new occistrm (user, passwd, db); demo->displayAllRows (); delete (demo); cout << "occistrm - done" << endl; }// end of int main (void);
|
Copyright © 2001, 2002 Oracle Corporation. All Rights Reserved. |
|