64,652
社区成员
发帖
与我相关
我的任务
分享
// occi1.cpp : 使用OCCI访问Oracle数据库的例子
//
#include <iostream>
#include <occi.h>
using namespace oracle::occi;
using namespace std;
int main(int argc, char* argv[])
{
// 用以连接数据库的参数
string strDBName, strUserName, strUserPassword;
Environment *env; // 环境
Connection *con; // 数据库连接
// 输入数据库名、用户名和口令
cout<<"enter database name:";
cin>>strDBName;
cout<<"enter user name:";
cin>>strUserName;
cout<<"enter password:";
cin>>strUserPassword;
// 创建运行环境
env = Environment::createEnvironment (Environment::DEFAULT);
// 建立数据库连接
con = env->createConnection (strUserName, strUserPassword, strDBName);
// 设置要执行的语句
Statement *stmt = con->createStatement
("BEGIN test_proc.test_getempinfo(:v1); END;");
// 注册输出参数
stmt->registerOutParam (1, OCCICURSOR, 30, "");
cout << "Executing the block :" << stmt->getSQL() << endl;
// 执行
stmt->executeUpdate ();
// 获取结果集
ResultSet *rst = stmt->getCursor(1);
// ---------------BEGIN 在VC++中以调试模式运行时,需修改这段代码-------------
int c1;
string c2;
try{
cout << "Printing the result set:" << endl;
cout <<"Number"<<"\t"<<"Names"<<endl;
// 读取并输出各记录
while(rst->next ())
{
c1=rst->getInt(1);
c2=rst->getString(2); // 在VC++6.0调试模式下,这里会报错
cout << c1<<"\t"<<c2 << endl;
}
// ---------------END 在VC++中以调试模式运行时,需修改这段代码-------------
}catch(SQLException ex)
{
cout<<"Exception thrown for displayAllRows"<<endl;
cout<<"Error number: "<< ex.getErrorCode() << endl;
cout<<ex.getMessage() << endl;
}
// 关闭结果集
stmt->closeResultSet (rst);
// 终止“语句”
con->terminateStatement (stmt);
cout << "occiproc - done" << endl;
// 断开数据库连接
env->terminateConnection (con);
Environment::terminateEnvironment (env);
return 0;
}
/*本例中的程序在Microsoft Windows和Linux平台中均可运行。通过程序的运行可以感觉到使用OCCI比ODBC调用的连接数据库速度要快很多,程序的执行效率较高。但这段代码在VC++6.0中,如果使用调试模式编译的话(使用Release模式则不存在此问题),由于内存分配上的原因,会出现异常。为了解决这个问题,需要将c2定义为指针,并从堆中分配内存。相应的代码段如下:*/
int c1;
string *c2;
try{
cout << "Printing the result set:" << endl;
cout <<"Number"<<"\t"<<"Names"<<endl;
// 读取并输出各记录
while(rst->next ())
{
c1=rst->getInt(1);
c2 = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(string));
*c2=rst->getString(2);
cout << c1<<"\t"<<c2 << endl;
HeapFree(GetProcessHeap(), 0, c2);
}