Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88889
  • 博文数量: 31
  • 博客积分: 886
  • 博客等级: 准尉
  • 技术积分: 245
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-02 10:45
文章分类

全部博文(31)

文章存档

2011年(31)

我的朋友

分类: C/C++

2011-01-18 13:08:11

在C++代码中,可以很好地通过调用OTL类方法,实现客户端和oracle的交互。
下面是一个简单的开发步骤:
 1、定义OTL_ORA9I等宏定义
 2、引用otlv4.h头文件,这个头文件可以从网上下载:
 3、初始化:otl_connect::otl_initialize();
 4、使用otl_connect对象的server_attach、session_begin方法连接数据库
 5、使用otl_stream或者otl_nocommit_stream方法执行sql语句。
       声明对象:
               otl_nocommit_stream osSeldb; 
                char *sql="select * from dual";
       执行sql:osSeldb.open(50, strSqldb.c_str(), db);
          执行取数据、插入数据等操作。。。
       关闭对象: osSeldb.close();
 
   注意:otl_stream,默认情况下,语句执行完毕后,会自动提交数据库,需慎用。
  
开发举例:
  
  1. #include <iostream.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. #define OTL_ORA9I // Compile OTL 4.0/OCI9i
  5. #define OTL_ORA_UTF8 // Enable UTF8 OTL for OCI9i
  6. #define OTL_STL
  7. #define OTL_UNCAUGHT_EXCEPTION_ON
  8. #define OTL_STL_NOSTD_NAMESPACE
  9. #define OTL_ORA9I
  10. #include <otlv4.h> // include the OTL 4.0 header file
  11. otl_connect db; // connect object
  12. void select()
  13. {
  14.   otl_stream i ( 1 , // buffer size
  15.                   "select to_char(cust_id),to_char(sub_bill_id),'12345 ','fftest' from user_table where rownum<100 " ,
  16.                                            // SELECT statement
  17.                   db // connect object
  18.    );
  19.   char f3[100];
  20.   int nLoop;
  21.   while ( !i.eof() )
  22.   {//循环取出每一行
  23.       for ( nLoop = 0; nLoop < *( i.ov_len ); nLoop++ )
  24.       {//循环取出每列
  25.           i >> f3;
  26.           cout << f3 << ",";
  27.       }
  28.       cout << endl;
  29.   }
  30. }

  31. int main()
  32. {
  33.   otl_connect::otl_initialize(); // initialize OCI environment
  34.   try
  35.   {
  36.       db.server_attach( "tnsname" );//
  37.       db.session_begin( "userName" ,"password" ); // connect to Oracle
  38.       select(); // select records from table
  39.   }
  40.   catch ( otl_exception& p )
  41.   {
  42.       // intercept OTL exceptions
  43.       cerr << p.msg << endl; // print out error message
  44.       cerr << p.stm_text << endl; // print out SQL that caused the error
  45.       cerr << p.var_info << endl; // print out the variable that caused the error
  46.   }
  47.   db.logoff(); // disconnect from Oracle
  48.   return 0;
  49. }
如果上面的代码保存在test.cpp文件里,则编译方法(HP):
  1. aCC +DA1.1 +Z -Wl,+s +u4 -ext -mt -Aa -g0 +d -I${ORACLE_HOME}/rdbms/demo -I${ORACLE_HOME}/rdbms/public -D_REENTRANT -D_THREAD_SAFE -DPTHREADS -DTHREAD -D_ILL_RECOVER_ -D_BILL_OPTIMAL_ -I. -o test test.cpp -L${ORACLE_HOME}/lib32 -lclntsh
阅读(7276) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~