Connecting c++ program with Oracle

2019-08-18 06:04发布

问题:

I'm trying to connect my C++ program to Oracle database(12.2).

My C++ program is (I am using g++ compiler in ubuntu),

#include <occi.h> 
#include <iostream> 

using namespace std;

int main()
{   oracle::occi::Environment *env = oracle::occi::Environment::createEnvironment();
    oracle::occi::Connection *conn = env->createConnection("bsk", "oraclepass");
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
}

I'm getting the error

undefined reference to `oracle::occi::Environment::createEnvironment(oracle::occi::Environment::Mode, void*, void* (*)(void*, unsigned long), void* (*)(void*, void*, unsigned long), void (*)(void*, void*))'
Employees.cpp:(.text+0x169): undefined reference to `oracle::occi::Environment::terminateEnvironment(oracle::occi::Environment*)'
collect2: error: ld returned 1 exit status

I'm new to database connectivity. Can you please help me with this?

回答1:

From Oracle's website, here is a valid example:

const string userName = "HR";
const string password = "password";
const string connectString = "";

Environment *env = Environment::createEnvironment();

{
   Connection *conn = env->createConnection(userName, password, connectString);
   Statement *stmt = conn->createStatement("SELECT blobcol FROM mytable");
   ResultSet *rs = stmt->executeQuery();
   rs->next();
   Blob b = rs->getBlob(1);
   cout << "Length of BLOB : " << b.length();
   ...
   stmt->closeResultSet(rs);
   conn->terminateStatement(stmt);
   env->terminateConnection(conn);
}

Environment::terminateEnvironment(env);

Your code seems to be in the right direction. So, it seems that some libraries are missing!

Again, from a different page on Oracle's website, here are the libraries required:

  • OCI Instant Client Data Shared Library (libociei.so on Linux and UNIX and oraociei12.dll on Windows); correct installation of this file determines if you are operating in Instant Client mode
  • Client Code Library (libclntsh.so.12.2 on Linux and UNIX and oci.dll on Windows)
  • Security Library (libnnz12.so on Linux and UNIX and orannzsbb12.dll on Windows)
  • OCCI Library (libocci.so.12.2 on Linux and UNIX and oraocci12.dll on Windows)

Make sure these libraries are installed on your machine.



回答2:

try this instead

$ g++ sample.C -I/opt/oracle/11.0.2/rdbms/public/ -L/opt/oracle/11.0.2/lib/ -locci -lclntsh

Replace /opt/oracle/11.0.2 with your oracle home path, it should work.

Find sample code from here