OCCI(Oracle C++ Call Interface):C++程序与Oracle数据库实现交互的应用程序接口,它以动态连接库的形式提供给用户。OCCI对OCI实行了对象级的封装,其底层仍是OCI
OCCI连接Linux下的Oracle数据库:
1 安装Linux下的oracle客户端
2 下载对应的oracle-instantclient-basic-10.2.0.4-1.i386.zip将其拷贝至Linux的Oracle账户并解压至instantclient_10_2目录
实现OCCI的六大步骤:
1 创建环境变量Environment
2 创建连接对象Connection
3 创建SQL语句的执行对象Statement
4 执行SQL语句(execute()函数,executeUpdate()函数,executeQuery()函数)
5 处理结果集ResultSet(查询结果)
6 关闭连接
在Linux的Oracle数据库下创建一个表用于操作
create table user_info ( user_id int not null primary key, user_name varchar2(100) ); //AddOcci.cc #include <iostream> #include <string> #include <occi.h> #pragma comment(lib,"oci.lib") #pragma comment(lib,"ociw32.lib") #pragma comment(lib,"oraocci10.lib") 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> #pragma comment(lib,"oci.lib") #pragma comment(lib,"ociw32.lib") #pragma comment(lib,"oraocci10.lib") 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之前:
执行DelOcci结果:
最新内容请见作者的GitHub页:http://qaseven.github.io/