使用OCCI连接Linux下Oracle数据库

OCCIOracleC++CallInterface):C++程序与Oracle数据库实现交互的应用程序接口,它以动态连接库的形式提供给用户。OCCIOCI实行了对象级的封装,其底层仍是OCI

OCCI连接Linux下的Oracle数据库:

1安装Linux下的oracle客户端

2下载对应的oracle-instantclient-basic-10.2.0.4-1.i386.zip将其拷贝至LinuxOracle账户并解压至instantclient_10_2目录

实现OCCI的六大步骤:

1创建环境变量Environment

2创建连接对象Connection

3创建SQL语句的执行对象Statement

4执行SQL语句(execute()函数,executeUpdate()函数,executeQuery()函数)

5处理结果集ResultSet(查询结果)

6关闭连接

LinuxOracle数据库下创建一个表用于操作

createtableuser_info

(

user_idintnotnullprimarykey,

user_namevarchar2(100)

);

//AddOcci.cc
#include <iostream>
#include <string>
#include "occi.h"
using namespace std;
using namespace oracle::occi;

/*******************************
 *向数据库中添加一条记录
 *******************************/

int main()
{
    //创建环境变量
    //Environment
    Environment *env = Environment::createEnvironment(Environment::OBJECT);

    //username是oracle的用户名
    //userpass是oracle的密码
    //connstr是oracle的连接字符串
    string username = "hahaya";
    string userpass = "hahaya";
    string connstr = "192.168.0.6:1521/orcl";
    //创建连接
    //connection
    Connection *conn = env->createConnection(username, userpass, connstr);

    if(conn == NULL)
    {
	cout << "access oracle failed..." << endl;
	return 0;
    }

    //创建一个SQL语句的执行对象
    //statement
    Statement *st = conn->createStatement();
    st->setSQL("insert into user_info values(1, 'hahaya')");
    st->executeUpdate();

    //关闭连接
    env->terminateConnection(conn);
    Environment::terminateEnvironment(env);

    return 0;
}


执行AddOcci程序之前:

执行AddOcci程序之后:

//ListOcci.cc
#include <iostream>
#include <string>
#include "occi.h"
using namespace std;
using namespace oracle::occi;

/*******************************
*查询表中数据
*******************************/

int main()
{
    Environment *env = Environment::createEnvironment(Environment::OBJECT);

    string username = "hahaya";
    string userpass = "hahaya";
    string connstr = "192.168.0.6:1521/orcl";
    Connection *conn = env->createConnection(username, userpass, connstr);
    
    Statement *st = conn->createStatement();
    st->setSQL("select * from user_info");
    ResultSet *rs = st->executeQuery();
    while(rs->next())
    {
	cout << "user id:" << rs->getInt(1) << "user name:" << rs->getString(2) << endl;;
    }

    st->closeResultSet(rs);

    env->terminateConnection(conn);
    Environment::terminateEnvironment(env);

    return 0;
}

执行ListOcci之前:

使用OCCI连接Linux下Oracle数据库

执行DelOcci结果:

你可能感兴趣的:(oracle数据库)