C++ OCCI 读写blob字段样例源码

#include 
#include 

#include 
#include "include/occi.h"
#define LINUXOCCI //避免函数重定义错误

using namespace std;
using namespace oracle::occi;

BYTE  *imageBuffer = NULL;
long g_bufSize = -1;


int WriteLob(Connection* conn, Blob& lob, UCHAR* pData, long nDataSize)
{
	unsigned int nChunkSize, nBufSize, nWrite, nOffset;
	UCHAR	*pi;
	int		retval = -1;

	try
	{
		if( pData==NULL || nDataSize<1 )
		{
			//lob.trim(0);
			lob.setNull();
			return 1;
		}

		nWrite = nOffset = 0;
		lob.open(OCCI_LOB_READWRITE);
#if 1
		while( nOffset < nDataSize )
		{
			nChunkSize = lob.getChunkSize();
			pi = pData + nOffset;
			nBufSize = (unsigned int)nDataSize - nOffset;
			if( nChunkSize < nBufSize )
				nWrite = nChunkSize;
			else
				nWrite = nBufSize;
			nWrite = lob.writeChunk(nWrite, pi, nBufSize, nOffset+1);
			nOffset += nWrite;
		}
#else
		Stream* pStream = lob.getStream();
		pStream->writeBuffer((char*)pData, (unsigned int)(ga_uint8)nDataSize);
		pStream->writeLastBuffer("", 0);
		lob.closeStream(pStream);
#endif
		lob.close();
		retval = 1;
	}
	catch(SQLException& e)
	{
		//DOSQLException(e, conn);
		cout<<"write blob异常"<createConnection(uesr, password, srvName);		//创建连接

	//添加数据懂啊数据库中

	CFile fpRead;
	CFileException e;
	fpRead.Open("1.jpg",CFile::modeRead | CFile::typeBinary,&e);

	g_bufSize = fpRead.GetLength();
	imageBuffer  = new BYTE[g_bufSize];

	int ret;

	try{
		if((ret = fpRead.Read(imageBuffer,g_bufSize))>0)
		{
			TRACE("ret = %d", ret);

			stmt = conn->createStatement("insert into image values(:1,:2)");

			int n = 1;
			stmt->setInt(1, n);

			Blob tmpBlob(conn);
			tmpBlob.setEmpty();
			stmt->setBlob(2, tmpBlob);

			stmt->executeUpdate();

			stmt->setSQL("select imagedata from image where id = :1 for update");
			stmt->setInt(1, n);

			ResultSet* rs = stmt->executeQuery();

			rs->next();

			tmpBlob = rs->getBlob(1);

			WriteLob(conn, tmpBlob, (UCHAR*)imageBuffer, g_bufSize);

			if(rs != NULL)	stmt->closeResultSet(rs);
			if(stmt != NULL)	conn->terminateStatement(stmt);
			conn->commit();

			cout<<"插入图片数据完成"<createStatement("select imagedata from image where id = :1 for update");
	//	stmt->setInt(1, n);

	//	rs = stmt->executeQuery();

	//	rs->next();

	//	Blob tmpBlob(conn);

	//	tmpBlob = rs->getBlob(1);
	//	tmpBlob.open(OCCI_LOB_READWRITE);

	//	blobLen = tmpBlob.length();

	//	imageBuffer  = new BYTE[blobLen];

	//	tmpBlob.read(blobLen,imageBuffer,blobLen,1);
	//	tmpBlob.close();

	//	CFile fpWrite;
	//	CFileException e;
	//	fpWrite.Open("2.jpg",CFile::modeWrite | CFile::modeCreate,&e);

	//	fpWrite.Write(imageBuffer,blobLen);
	//	fpWrite.Close();

	//	if(rs!=NULL)
	//	stmt->closeResultSet(rs);
	//	if(stmt!=NULL)
	//	conn->terminateStatement(stmt);

	//	env->terminateConnection(conn);

	//	//释放空间	
	//	if(imageBuffer!=NULL)
	//		delete []imageBuffer;
	//

	//	cout<<"读取图片完成"<

你可能感兴趣的:(C++ OCCI 读写blob字段样例源码)