Connecting to Oracle via OCCI (c + +)

Source: Internet
Author: User
Tags getmessage stmt access database

OCCI Introduction

The occi:oracle C + + Call Interface (OCCI), Oracle's C++API, allows you to access the Oracle database using object-oriented features, native classes, and C + + language methods.

Occi Advantage is based on standard C + + and object-oriented design, high efficiency, suitable for developing C/S mode program, software middle layer; Occi feature full support Sql/plsql provides resiliency options for growing users and requests to use user-defined types, such as classes in C, Provides a seamless interface to support all Oracle data types and LOB types to access database metadata Occi header files and dynamic link libraries

OCCI header File

? occi.h?occicommon.h?occicontrol.h?occidata.h?occiobjects.h

OCCI Library

? Libocci.so/libocci.a/oraocci9.dll Building Applications Step 1: InitializeOcci by creating aobjects of the environmentComplete the initialization work. You can create a database connection through environment for other operations to create environment, you should call the static method of the Environment class createenvironment ()Example: [CPP]View Plaincopy
  1. <span style= "COLOR: #000000;" > //include 1 header file for all OCCI classes/interfaces   
  2. #include <occi.h>   
  3. //create Environment   
  4. Environment *env = environment::createenvironment (); //Create a Connection object pointer   
  5. //use the environment instance to create connections,   
  6. //database Access   
  7. ...
  8. //terminate environment by calling static method   
  9. //environment::terminateenvironment   
  10. Environment::terminateenvironment (env); //Close </span>   
Step two: Connect to the databaseConnect to the database byConnection Classobject instance implementation that calls the environment class. createconnection ()Method can create a connection object;

[CPP]View Plaincopy
    1. Connection *environment::createconnection ( const string &username,const string &password, Const string &connectstring)

After a successful connection to the database, you can use it to access the data, execute the SQL statement; environment::terminateconnection ()Disconnect; Example: [CPP]View Plaincopy
  1. //first Need Environment   
  2. Environment *env = environment::createenvironment ();
  3. Connection *conn=env->createconnection ("Scott", "Tiger", "" ");
  4. //3rd parameter is db name/tns alias   
  5. .. //database Access–use the Connection object   
  6. ..
  7. ..
  8. //logoff and Terminate connection   
  9. Env->terminateconnection (conn); //Disconnect   
Step Three: Execute Sql/plsqlStatement ClassUsed to execute the SQL/PLSQL statement and get the return result.ResultSet classUsed to process the results of a select query. OCCI provides a unified approach to binding or acquiring all types of data

-Setxxx method for statement

-GetXXX method for statement & ResultSet

Occi automatically handles conversions between types. How to use: Use Connection:: createstatement ()Creates a statement object specifying the SQL command (ddl/dml/query) as a parameter

Connection::createstatement (string &sql);

Statement::setsql(string &sql);

Statement::Execute(string &sql); -can be used for any SQL, returnsstatus

Statement::executeupdate (string &sql); -Returns Insert/update/delete count

Statement::executequery (string &sql); -Returns ResultSet (result set)

Use the Setxxx method to pass the value you want to bind to the input using the appropriate execute method to execute SQL for the select query, using the ResultSet object to handle the simple DML insert example that returns the result: [CPP]View Plaincopy
    1. //createstatement () on Connection class gives a Statement   
    2. //instance   
    3. Statement *stmt = conn->createstatement ("INSERT into Dept (Deptno,dname, Loc) VALUES (1, ' ACCOUNTS ', ' ZONE1 '");
    4. //executeupdate for all Insert/update/delete   
    5. Stmt->executeupdate ();
    6. Conn->terminatestatement (stmt);
Examples of DML using binding parameters: [CPP]View Plaincopy
  1. Statement *stmt = conn->createstatement ("INSERT INTO
  2. EMP (Empno,ename) VALUES (: 1,: 2) ");
  3. //1 and 2 are bind placeholders   
  4. int  empno = 2;
  5. String empname = "JOHN W";
  6. //first parameter is bind position, second is value   
  7. Stmt->setint (1, empno);
  8. Stmt->setstring (2, EmpName);
  9. Stmt->executeupdate ();
[CPP]View Plaincopy
Execute a SELECT query and process the results: [CPP]View Plaincopy
  1. Statement *stmt = conn->createstatement ("Select Empno,
  2. ename, Sal from EMP where hiredate >=: 1 ");
  3. //automatically converted to Date   
  4. Stmt->setstring (1, "01-jan-1987");
  5. //executequery returns a ResultSet   
  6. ResultSet *rs = Stmt->executequery ();
  7. //resultset::next fetches rows and returns FALSE   
  8. //when no more rows   
  9. while (rs->next () = = true)
  10. {
  11. //get values using the GetXXX methods of ResultSet   
  12. Empno = Rs->getint (1);
  13. EmpName = rs->getstring (2);
  14. Empsalary = Rs->getfloat (3);
  15. }
  16. Stmt->closeresultset (RS); //to Free Resources   

Execute PL/sql:

To perform PL/SQL, you should specify a PL/SQL block to use SETXXX to pass all input parameters (in andin/out) to the Plsql function or procedure using statement when creating statement:: Registeroutparam to specify the out parameter, the size of the parameter is specified by Statement::setmaxparamsize using Statement::execute () execution pl/ SQL uses the GetXXX method to get the results of function execution and out/in out parameters example: calling PL/SQL function/procedure

[CPP]View Plaincopy
  1. //plsql Function:functioncalculatebonus (EmpNo innumber,
  2. //Empstatus in Out VARCHAR2,   
  3. //Bonus out number) RETURN VARCHAR2
  4. //call function usinganonymous block   
  5. Statement *stmt = Conn->createstatement ("Begin:1: = Calculatebonus (
  6. : 2,: 3,: 4); end; ");
  7. //bind position 1 is thefunction ' s return value   
  8. Stmt->setint (2, 100); //in parameter   
  9. Stmt->setstring (3, "Active"); //in out parameter   
  10. //call Registeroutparam for each out parameter   
  11. Stmt->registeroutparam (1, occistring, 1000); //function ' Sreturn value   
  12. Stmt->setmaxparamsize (1, 100); //setmaxparamsize for STRING types   
  13. Stmt->registeroutparam (4, occifloat);
  14. Stmt->execute ();
  15. //use GetXXX methods of Statement to get outparameters, return value   
  16. String msg = stmt->getstring (1); //function return value   
  17. String newstatus = stmt->getstring (3); //in out parameter   
  18. float bonus = stmt->getfloat (4); //out parameter   

Step four: error handlingOcci uses the C + + exception mechanism to return all error messages applications should use the Try-catch structure to handle exceptions thrown by the exception belonging to the SqlException type, which inherits from standard C + + The exception class in can use the GetErrorCode and GetMessage methods to obtain an Oracle error message

Example:

Handling Oracle and C + + STL errors separately

[CPP]View Plaincopy
  1. Try   
  2. {
  3. ResultSet *rs = Stmt->executequery ();
  4. while (Rs->next ())
  5. ..........
  6. }
  7. Catch (SQLException &oraex) //oracle/occi Errors   
  8. {
  9. int errno = Oraex->geterrorcode (); //returns the ORA number   
  10. String errmsg = Oraex->getmessage ();
  11. //more Application Error handling   
  12. }
  13. Catch (Exception &ex) //any other C++/stl error   
  14. {
  15. cout << "Error" << ex.what () << Endl;
  16. }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.