Oracle的C++调用接口(OCCI)

长平狐 发布于 2013/12/25 17:25
阅读 563
收藏 0

以前研究过一些数据库接口,比如OCI,今天又特意研究了OCCI,OCCI是在OCI的基础上封装的一层面向C++开发者的一套类库,采用面向对象的方法组织,而OCI是C语言接口,函数调用相当复杂,并且封装也不太容易。废话少说,先上代码吧。

 

#include <iostream>
#include <occi.h>
#include <assert.h>

using namespace oracle::occi;
using namespace std;

int main () 
{
	Environment *env = NULL;
	Connection *conn = NULL;
	Statement *stmt = NULL;
	ResultSet *rs = NULL;

	string username = "scott";						//用户名
	string password = "tiger";						//密码
	string connstring = "//localhost:1521/ORCL";	//连接字符串
	string sql,strname;
	int errNum = 0;
	string errMsg = "";

	env = Environment::createEnvironment(); //创建一个环境变量
	try 
	{
		assert(env != NULL);
		conn = env->createConnection(username,password,connstring); //创建一个数据库连接对象
		stmt = conn->createStatement(); //创建一个Statement对象
	} 
	catch (SQLException ex) 
	{
		errNum = ex.getErrorCode();
		errMsg = ex.getMessage();
		cout << "Error Number : "<< errNum << endl; //取出异常代码
		cout << errMsg << endl; //取出异常信息
	}

	sql = "SELECT ID,NAME FROM STUDENT WHERE ID >= :1";  //拼接一个SQL语句
	int id = 2;
	stmt->setSQL(sql); //设置SQL语句到Statement对象中
	stmt->setInt(1,id);
	try 
	{
		char buffer[4096];			//缓冲区
		rs =  stmt->executeQuery();//执行SQL语句
		int recordCnt = rs->getNumArrayRows();
		rs->setCharacterStreamMode(2,1000);
		while (rs->next()) 
		{ 
			//一条一条的取数据
			unsigned int length = 0;
			unsigned int size = 500;
			Stream *stream = rs->getStream(2);
			while (stream->status() == Stream::READY_FOR_READ)
			{
				length += stream->readBuffer(buffer +length, size);	  
			}
			cout << "Read " << length << " bytes into the buffer" << endl;
		}
		cout << "SELECT ―― SUCCESS" << endl;
	} 
	catch (SQLException ex) 
	{
		cout << "Error Number : "<< ex.getErrorCode() << endl; //取出异常代码
		cout << ex.getMessage() << endl; //取出异常信息
	}

	conn->terminateStatement(stmt); //终止Statement对象
	env->terminateConnection(conn); //断开数据库连接
	Environment::terminateEnvironment(env); //终止环境变量

	return 1;
}


 


原文链接:http://blog.csdn.net/zhouxuguang236/article/details/7565049
加载中
返回顶部
顶部