OCILIB实例

下载地址:http://sourceforge.net/projects/orclib/

 OCILIB实例:

#include <iostream>
#include "ocilib.h"

//错误处理
void err_handler(OCI_Error *err)
{
    int   err_type = OCI_ErrorGetType(err);
    char *err_msg  = (char*)OCI_ErrorGetString(err);

    printf("%s - %s\n", err_type == OCI_ERR_WARNING ? "warning" : "error", err_msg);
}

int main(int argc, char *argv[])
{
	int nRet = 0;
	OCI_Connection* cn = NULL;
	OCI_Statement* st = NULL;
	OCI_Resultset* rs = NULL;
	
	//初始化OCI库
	nRet = OCI_Initialize(NULL, NULL, OCI_ENV_DEFAULT);
	if(!nRet)
	{
		std::cout << "OCI_Initialize fail" << std::endl;
		return -1;
	}
	
	do
	{
		std::cout << "compile version:" << OCI_GetOCICompileVersion() << std::endl;

		std::cout << "runtime version:" << OCI_GetOCIRuntimeVersion() << std::endl;

		//建立联接:tns:cctt1;username:d10086;password:d10086
		cn = OCI_ConnectionCreate("cctt1", "D10086", "D10086", OCI_SESSION_DEFAULT);
		if(NULL == cn)
		{
			std::cout << "OCI_ConnectionCreate fail" << std::endl;
			err_handler(OCI_GetLastError());
			nRet = -2;
			break;
		}

		printf("Server major    version : %i\n",   OCI_GetServerMajorVersion(cn));
		printf("Server minor    version : %i\n",   OCI_GetServerMinorVersion(cn));
		printf("Server revision version : %i\n\n", OCI_GetServerRevisionVersion(cn));
		printf("Connection      version : %i\n\n", OCI_GetVersionConnection(cn));

		//建立声明
		st = OCI_StatementCreate(cn);
		if(NULL == st)
		{
			std::cout << "OCI_StatementCreate fail" << std::endl;
			err_handler(OCI_GetLastError());
			nRet = -3;
			break;
		}

		//绑定变量
		char *value = "E3";
		//准备SQL语句,用 :value 占位符占位
		if(!OCI_Prepare(st, "select * from tb_smss_message where smsid=:value"))
		{
			std::cout << "OCI_Prepare fail" << std::endl;
			err_handler(OCI_GetLastError());
			nRet = -4;
			break;
		}
		//绑定变量,用变量替换占位符
	    if(!OCI_BindString (st, ":value", value, strlen(value)))
	    {
	    	std::cout << "OCI_BindString fail" << std::endl;
	    	err_handler(OCI_GetLastError());
	    	nRet = -5;
	    	break;
	    }
	    //执行声明
		if(!OCI_Execute(st))
		{
			std::cout << "OCI_Execute fail" << std::endl;
	    	err_handler(OCI_GetLastError());
	    	nRet = -6;
	    	break;
		}


/*		if(!OCI_ExecuteStmt(st, "select * from tb_smss_message"))
		{
			std::cout << "OCI_ExecuteStmt fail" << std::endl;
			err_handler(OCI_GetLastError());
			nRet = -4;
			break;
		}
*/		
		//得到返回值集
		rs = OCI_GetResultset(st);
		if(NULL == rs)
		{
			std::cout << "OCI_GetResultset fail" << std::endl;
			err_handler(OCI_GetLastError());
			nRet = -5;
			break;
		}
		
		//枚举返回值集
		while (OCI_FetchNext(rs))
		{
			printf("%i - %s\n", OCI_GetString(rs, 1), OCI_GetString(rs,2));
		}
	}while(0);
	
	//释放返回集
	if(rs)
		OCI_ReleaseResultsets (st);
	
	//清除声明
	if(st)
		OCI_StatementFree(st);
	
	//清除连接
	if(cn)
		OCI_ConnectionFree (cn);
	
	//清除OCI库
	OCI_Cleanup();
	
	return EXIT_SUCCESS;
}


 

你可能感兴趣的:(sql,server,session,null)