在C++代码中,可以很好地通过调用OTL类方法,实现客户端和oracle的交互。
下面是一个简单的开发步骤:
1、定义OTL_ORA9I等宏定义
2、引用otlv4.h头文件,这个头文件可以从网上下载:http://otl.sourceforge.net/otlv4_h.zip
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,默认情况下,语句执行完毕后,会自动提交数据库,需慎用。
开发举例:
- #include
<iostream.h>
- #include
<stdio.h>
- #include
<time.h>
- #define OTL_ORA9I
// Compile OTL 4.0/OCI9i
- #define OTL_ORA_UTF8
// Enable UTF8 OTL for OCI9i
- #define OTL_STL
- #define OTL_UNCAUGHT_EXCEPTION_ON
- #define OTL_STL_NOSTD_NAMESPACE
- #define OTL_ORA9I
- #include
<otlv4.h>
// include the OTL 4.0 header file
- otl_connect db;
// connect object
- void select()
- {
- otl_stream i ( 1
, // buffer size
- "select to_char(cust_id),to_char(sub_bill_id),'12345 ','fftest' from user_table where rownum<100 "
,
- // SELECT statement
- db // connect object
- );
- char f3[100];
- int nLoop;
- while (
!i.eof()
)
- {//循环取出每一行
- for ( nLoop
= 0; nLoop
< *( i.ov_len
); nLoop++
)
- {//循环取出每列
- i >> f3;
- cout
<< f3 <<
",";
- }
- cout <<
endl;
- }
- }
- int main()
- {
- otl_connect::otl_initialize();
// initialize OCI environment
- try
- {
- db.server_attach(
"tnsname" );//
- db.session_begin(
"userName" ,"password"
);
// connect to Oracle
- select();
// select records from table
- }
- catch ( otl_exception& p
)
- {
- // intercept OTL exceptions
- cerr << p.msg
<<
endl; // print out error message
- cerr << p.stm_text
<<
endl; // print out SQL that caused the error
- cerr << p.var_info
<<
endl; // print out the variable that caused the error
- }
- db.logoff();
// disconnect from Oracle
- return 0;
- }