Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Connect C++ with Oracle (http://www.go4expert.com/articles/connect-cpp-oracle-t5442/)

Shishir191 24Jul2007 16:53

Connect C++ with Oracle
 
Oracle C++ Call Interface (OCCI) is an Application Programming Interface (API) that provides C++ applications access to data in an Oracle database. This API is a significant improvement to the Oracle Call Interface (OCI) API as far as ease of use is concerned. Engineers who have written JDBC (Java Database Connectivity) code will find the OCCI API to be quite similar to that of JDBC

1) The table that is used in the example code is:



Code: SQL

CREATE TABLE EMP(
    empno     NUMBER,
    ename     VARCHAR2(10),
    hireDate  Date);

2) Database Query : Select the contents of the EMP table



Code: Cpp

#include <DbManager.h>
#include <iostream>

using namespace std;

using namespace oracle::occi;

const string sqlString("select empno, ename, hiredate from emp");

const string dateFormat("DD-MON-YYYY HH24:MI:SS");

int main(int argc, char **argv)

{
    if (argc != 2)
    {
        cerr << "\nUsage: " << argv[0] << " <db-user-name>\n" << endl;
        exit(1);
    }
   
    // Initialize OracleServices
   
    DbManager* dbm = NULL;
   
    OracleServices* oras = NULL;
   
    Statement *stmt = NULL;
   
    ResultSet *resultSet = NULL;
   
    try
    {
       
        // Obtain OracleServices object with the default args.
       
        dbm = new DbManager(userName);
       
        oras = dbm->getOracleServices();
       
        // Obtain a cached connection
       
        Connection * conn = oras->connection();
       
        // Create a statement
       
        stmt = conn->createStatement(sqlString);
       
        int empno;
       
        string ename;
       
        Date hireDate;
       
        string dateAsString;
       
        // Execute query to get a resultset
       
        resultSet = stmt->executeQuery();
       
        while (resultSet->next())
        {
           
            empno = resultSet->getInt(1)// get the first column returned by the query;
           
            ename = resultSet->getString(2)// get the second column returned by the query
           
            hireDate = resultSet->getDate(3)// get the third column returned by the query
           
            dateAsString="";
           
            //You cannot check for null until the data has been read
           
            if (resultSet->isNull(1))
            {
                cout << "Employee num is null... " << endl;
            }
            if (resultSet->isNull(2))
            {
                cout << "Employee name is null..." << endl;
            }
            if (resultSet->isNull(3))
            {
                cout << "Hire date is null..." << endl;
            }
            else
            {
                dateAsString=hireDate.toText(dateFormat);
            }
            cout << empno << "\t" << ename << "\t" << dateAsString << endl;
           
        }
       
        // Close ResultSet and Statement
       
        stmt->closeResultSet(resultSet);
       
        conn->terminateStatement(stmt);
       
        // Close Connection and OCCI Environment
       
        delete dbm;
       
    }
    catch (SQLException& ex)
    {
        if (dbm != NULL)
        {
            dbm->rollbackActions(ex, stmt, resultSet); // free resources and rollback transaction
        }
    }
    catch (ExoException& ex1)
    {
        cerr << "\nCaught ExoException:\n" << ex1.getExceptionText() << endl;
        exit(2);
    }
   
    return 0;
}


shabbir 24Jul2007 18:23

Re: Connect C++ with Oracle
 
Nicely coded and commented.

seeguna 26Jul2007 08:01

Re: Connect C++ with Oracle
 
Good one

Shishir191 26Jul2007 13:17

Re: Connect C++ with Oracle
 
Thanks

pradeep 27Jul2007 14:21

Re: Connect C++ with Oracle
 
Really cool! :-)

Shishir191 29Jul2007 21:02

Re: Connect C++ with Oracle
 
Thanks.

kush_2207 30Jul2007 19:07

Re: Connect C++ with Oracle
 
gr8 post !

Shishir191 30Jul2007 19:45

Re: Connect C++ with Oracle
 
Thanks.

kush_2207 3Aug2007 03:03

Re: Connect C++ with Oracle
 
Getting compile-time errors like Not able to find dbmanager.h header file....
Please Help !
Thanx.

Shishir191 13Aug2007 23:12

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by kush_2207
Getting compile-time errors like Not able to find dbmanager.h header file....
Please Help !
Thanx.

Hi Kush,

Sorry for the delay. Sorry, there is no need to include "dbmanager.h" by mistake i have included it.

You have to include "occi.h" like #include<occi.h> in your program.

Note one thing more this code will not work for every compiler. Either you have to use visual C++7.
Or you can use gcc comipler version 3.4.3. If you are using gcc comipler in linux then you have to download occi libraries from Oracle web site.

And you have to copy these files into your $ORACLE_HOME/lib.
If you have installed oracle client in your machine the it contains one "rdms" folder which contain one "demo" folder . From that folder you can use "demo_xe.mk" to compile your file.

If you have any further query then you can ask me.

shabbir 14Aug2007 08:24

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by Shishir191
Sorry for the delay. Sorry, there is no need to include "dbmanager.h" by mistake i have included it.

You have to include "occi.h" like #include<occi.h> in your program.

Why don't you edit the code to have the correct version.

Shishir191 14Aug2007 09:57

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by shabbir
Why don't you edit the code to have the correct version.

Ok.

Shishir191 14Aug2007 10:00

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by shabbir
Why don't you edit the code to have the correct version.

Hi Shabbir,
Can i edit the existing code ? Or i have to upload the new code. If it is possible to edit the code then pls tell from where i can do this.

shabbir 14Aug2007 10:39

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by Shishir191
Hi Shabbir,
Can i edit the existing code ? Or i have to upload the new code. If it is possible to edit the code then pls tell from where i can do this.

You don't have any attachment and so all you need to do is edit the post and update the code accordingly.

kush_2207 15Aug2007 01:46

Re: Connect C++ with Oracle
 
Hi Shishir,
I have attached the VC++ 6.0 version connection with Oracle. It is overall the same code which you have listed out in this thread. I have also included oci.h from the Oracle Include directory. Still i am getting problems -> Please check out.

shabbir 15Aug2007 09:43

Re: Connect C++ with Oracle
 
I have removed the attachment. Please do not attach the complete project / solution and ask for someone to debug it. You can always discuss the issue if you have some problem.

Peter_APIIT 22Sep2007 13:51

Re: Connect C++ with Oracle
 
How about an article explain how to connect C++ to SQL ?

I using MS Visual Studio 2005.

I really noob to database as well as C++.

Thanks for your help. Your help is greatly appreciated by me and others.

Peter_APIIT 27Sep2007 15:35

Re: Connect C++ with Oracle
 
Any guide or tutorial where i can start to learn connect C++ with msssql ?

Thanks for your help.

vkiransrinivas 10Oct2007 10:54

Re: Connect C++ with Oracle
 
Thanks for sending

Shishir191 25Oct2007 11:10

Re: Connect C++ with Oracle
 
Thanks for your good comments.

Shishir191 7May2008 17:05

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by Shishir191
Thanks for your good comments.

Thanks to all

ZeroMaru 29Aug2008 01:06

Re: Connect C++ with Oracle
 
I tried compiling this with:

devc++
miscrosoft visual studio 2003 (vc++ 7)
microsoft visual studio 2005 (8)
microsoft visual studio 2008 (9)

i dont know if im doing somthing wrong or what, but i keep getting this errors:
^
Code:

d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(31) : error C2065: 'DbManager' : identificador no declarado
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(31) : error C2065: 'dbm' : identificador no declarado
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(33) : error C2065: 'OracleServices' : identificador no declarado
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(33) : error C2065: 'oras' : identificador no declarado
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(44) : error C2061: error de sintaxis : identificador 'DbManager'
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(44) : error C3861: 'dbm': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(46) : error C2227: el operando izquierdo de '->getOracleServices' debe señalar a class/struct/union
        el tipo es ''unknown-type''
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(46) : error C3861: 'oras': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(46) : error C3861: 'dbm': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(50) : error C2227: el operando izquierdo de '->connection' debe señalar a class/struct/union
        el tipo es ''unknown-type''
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(50) : error C3861: 'oras': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(109) : error C2541: 'delete' : no se pueden eliminar objetos que no sean punteros
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(109) : error C3861: 'dbm': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(114) : error C3861: 'dbm': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(116) : error C2227: el operando izquierdo de '->rollbackActions' debe señalar a class/struct/union
        el tipo es ''unknown-type''
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(116) : error C3861: 'dbm': no se encontró el identificador, ni siquiera con búsqueda dependiente de argumentos
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(119) : error C2061: error de sintaxis : identificador 'ExoException'
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(119) : error C2310: los controladores de tipo catch deben especificar un tipo
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(121) : error C2065: 'ex1' : identificador no declarado
d:\rcocchiararo\Mis documentos\Visual Studio Projects\test\test.cpp(121) : error C2228: el operando izquierdo de '.getExceptionText' debe tener el tipo class/struct/union
        el tipo es ''unknown-type''

is dbmanager.h or some other library responsable for defining all those variables/things ?

i have tried with oracle client and oracle server 10g installed.
I downloaded occi for visual studio 2005 (vs8), and well, i dont know what else to do :(

ZeroMaru 29Aug2008 01:15

Re: Connect C++ with Oracle
 
to bad i see no edit button, anyway, i forgot to mention that im new to visual studio, so i may be missing some configuration or chosing the wrong type of project, dunno :(

shabbir 29Aug2008 09:19

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by ZeroMaru
to bad i see no edit button, anyway, i forgot to mention that im new to visual studio, so i may be missing some configuration or chosing the wrong type of project, dunno :(

It will come when you reach a double digit post count.

ZeroMaru 29Aug2008 22:40

Re: Connect C++ with Oracle
 
i see

(i was kinda exited about a posible solution for my "problem" when i saw i had a mail from this forum :p )

ZeroMaru 29Aug2008 22:42

Re: Connect C++ with Oracle
 
ahhhhhhh heck

the moment i finished posting the last mesage i saw i had a reply on another forum telling me this about my problem:

Quote:

That's simply because DbManager and OracleServices are not OCCI classes, but likely wrappers around OCCI classes from the poster.

For pure OCCI examples, look in your server install, in RDBMS\demo\occidml.cpp for example on windows. --DD
any ideas about that either ? i find it strange that this example is all over the web and im the only one unable to compile it.

xpi0t0s 2Oct2008 23:15

Re: Connect C++ with Oracle
 
You're not the only one unable to compile it. The code is dependent on dbmanager.h and won't build without it, and dbmanager.h (and any library or other source code it relates to) is not referenced anywhere. Simply removing #include <dbmanager.h> WON'T solve the problem because there are references within the code, i.e.:
Code:

DbManager* dbm = NULL;
dbm = new DbManager(userName);
oras = dbm->getOracleServices();
Connection * conn = oras->connection();
delete dbm;
dbm->rollbackActions(ex, stmt, resultSet);

OP: how about providing dbmanager.h and dbmanager.cpp, or at least stating where it can be found, so that people can actually use this example?

imrose_suleman 18Oct2008 11:26

Re: Connect C++ with Oracle
 
created an employee table in sql and coded in cpp....i compiled using g++ compiler...but getting lot of errors ....can u pls help me out..

imrose_suleman 18Oct2008 11:32

Re: Connect C++ with Oracle
 
there is no clear solution to this problem..still unable to fix this prob in comp....
i need to do case study..and i need it urgently...

xpi0t0s 18Oct2008 12:57

Re: Connect C++ with Oracle
 
I'm trying to fix the code but I keep getting unexplained crashes.
In the meantime use some of the OCCI demo programs from $ORACLE_HOME/rdbms/demo. In 10g these are installed from the Companion disk.

Mclarry 19Oct2008 05:55

Re: Connect C++ with Oracle
 
What is connect c++ with oracle used for? Pls explain cos im a starter hacker.

shabbir 19Oct2008 11:46

Re: Connect C++ with Oracle
 
Quote:

Originally Posted by Mclarry
What is connect c++ with oracle used for? Pls explain cos im a starter hacker.

If you are not sure what is C++ and oracle then you should post your query in the new thread and not just jump into any thread saying you are new to hacking. This thread is also not about hacking BTW

gandu 6Nov2008 12:40

Re: Connect C++ with Oracle
 
Hi,

Its really very good

Thanks

happyz 22Nov2008 19:26

Re: Connect C++ with Oracle
 
Gud and will give it a try

prabhat1 24Nov2008 09:10

Re: Connect C++ with Oracle
 
Hi..Shishir ...very Nice code .....But I need C++ connectivity with DB2 can u suggest some code as well as configuration requirements for connecting C++ with DB2......

thanks in advance.............

hkp819 5Dec2008 15:29

Re: Connect C++ with Oracle
 
great. It is great program. I confused to understand it. Because i am not good in programming. But it is not too much complex.
thanks

skp819 9Dec2008 17:31

Re: Connect C++ with Oracle
 
thank for share it. It is helpful for me.
thanks once again.

vishy_acts 23Apr2010 12:01

Re: Connect C++ with Oracle
 
Hi
This code is not working on Unix Solaris .
Its giving error Could not open include file<DbManager.h>
what is the solution ?

trentven 13Mar2012 12:31

Re: Connect C++ with Oracle
 
Hi,

Am trying to connect with this piece of code from Dev C++ 4.9.9.2. I believe that Dev C++ is using GCC compiler....

Compilation is success.

But the problem is when i try to execute the code am getting "Linker" error.

Any Idea about how resolve the above error.... Please advice....

With Regards,
Venkat Raghaven

trentven 13Mar2012 12:33

Re: Connect C++ with Oracle
 
I even tried with the "OCI examples" but no go....

Still the same "Linker" error....

Am really Stuck with this..... Please help....

With Regards,
Venkat Raghaven


All times are GMT +5.5. The time now is 12:19.