⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ado.cpp

📁 一个用来学习用的ADO类 有一定得实用价值哦
💻 CPP
字号:
#include "stdafx.h"
#include "ado.h"

ado::ado()
{
	::CoInitialize(NULL);
	try
	{
	m_pConnection.CreateInstance(__uuidof(Connection));
//	_bstr_t strConnect="Provider=SQLOLEDB;SERVER=127.0.0.1,1433;Database=Exam;uid='';pwd='';";
	
//	_bstr_t strConnect="ODBC;Provider=SQLOLEDB;Driver={SQL Server};Server=127.0.0.1;User ID=sa;Pwd='';Database=Exam";

 	//_bstr_t strConnect="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=test;Data Source=FLY-FA37535DEF2";

	////_bstr_t strConnect="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Exam;Data Source=FLY-FA37535DEF2";
	 //  _bstr_t strConnect="Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Exam;Data Source=FLY-FA37535DEF2";
 _bstr_t strConnect="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=.";	

	

//	 _bstr_t strConnect="Providr=SQLOLEdb;Network Library=DBMSSOCN;Data Source=127.0.0.1,1433;Initial Catalog=Exam;User ID=sa;Password=''";
	 //远程连接数据库的标准字符串
	//_bstr_t strConnect="driver={SQL server};server=127.0.0.1;DATABASE=db_Client;uid=sa;pwd=";
	//_bstr_t strConnect="dsn=db_client";
	//ntServer
	HRESULT hr=m_pConnection->Open(strConnect,"sa","",0);
	if(FAILED(hr))
	{AfxMessageBox("不能连接数据库  source");}

	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	
	}
}
ado::~ado()
{
	//m_pRecordset->Close();
///	m_pConnection->Close();
//	m_pRecordset=NULL;
//	m_pConnection=NULL;
//	::CoUninitialize();

}
bool ado::Open(CString srecordset, UINT adCmd)
{
	
	try{
	 m_pRecordset=m_pConnection->Execute((_bstr_t)srecordset,NULL,adCmd);
	}
	catch(_com_error&e)
	{
		this->GetErrors(e);
		return false;
	}
	return true;
}
int ado::GetRecordCount()
{
	int nCount=0;
	try{
	
		m_pRecordset->MoveFirst();
	}
	catch(...)
	{
		return 0;
	}
	if(m_pRecordset->adoEOF)
		return 0;
	while (!m_pRecordset->adoEOF)
	{
		m_pRecordset->MoveNext();
		nCount=nCount+1;	
	}
	m_pRecordset->MoveFirst();
	return nCount;
}
void ado::GetErrors(_com_error eErrors)
{
	/*CString string;
	CFile file;
	
	file.Open("Error.Rxe",CFile::modeWrite|CFile::modeNoTruncate);
	ErrorsPtr pErrors=cnn->GetErrors();
	if (pErrors->GetCount()==0)	
	{
		string=(char*)(_bstr_t)eErrors.ErrorMessage();
		file.Write(string+"\r\n",string.GetLength()+1);
		//::AfxMessageBox(string);
	}
	else
	{
		for (int i=0;i<pErrors->GetCount();i++)
		{
			_bstr_t desc=pErrors->GetItem((long)i)->GetDescription();
			string=(char*)desc;
			file.Write(string+"\r\n",string.GetLength()+1);
			//::AfxMessageBox(string);
		}
	}
	file.Close();
	*/
	ErrorsPtr pErrors=m_pConnection->GetErrors();
	if (pErrors->GetCount()==0)	
		MessageBox(NULL,eErrors.ErrorMessage(),"错  误",MB_OK|MB_ICONEXCLAMATION);	
	else
	{
		for (int i=0;i<pErrors->GetCount();i++)
		{
			_bstr_t desc=pErrors->GetItem((long)i)->GetDescription();
			MessageBox(NULL,desc,"错  误",MB_OK|MB_ICONEXCLAMATION);
		}
	}
}
//_RecordsetPtr&

void ado::rstOpen(CString TSQL)//打开记录集
{
	try
	{
	_bstr_t bstrSQL=TSQL.AllocSysString();
	m_pRecordset.CreateInstance(__uuidof(Recordset));
	//m_pRecordset->Open(bstrSQL,(IDispatch*)m_pConnection,adOpenDynamic,adLockOptimistic,adCmdText);
	m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
	}
	catch(_com_error e)
	{
	m_pRecordset=m_pConnection->Execute((_bstr_t)TSQL,NULL,adCmdText);
	//return false;
	}
	//return m_pRecordset;
}

CString ado::GetFieldValue(CString Field)
{
    _variant_t Thevalue;
	CString temp;
	
    Thevalue=m_pRecordset->GetCollect((_bstr_t)Field);
	if(Thevalue.vt==VT_EMPTY ||Thevalue.vt==VT_NULL)
		temp="";
	else
	{
		temp=(char*)(_bstr_t)Thevalue;
		temp.TrimRight();
		temp.TrimLeft();
	}
	
	return temp;
}
bool ado::MovePrevious()
{
	try
	{
	m_pRecordset->MovePrevious();
	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	return false;
	}
	return true;
}
bool ado::Move(int nRecordNum)
{
	try
	{
		if(!m_pRecordset->BOF)
		{
			m_pRecordset->MoveFirst();
		}
			m_pRecordset->Move(nRecordNum);
	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	return false;
	}
	return true;
}
bool ado::MoveNext()
{
	try
	{
	
	m_pRecordset->MoveNext();

	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	return false;
	}
	return true;
}
bool ado::MoveFirst()
{
	try
	{
	m_pRecordset->MoveFirst();
	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	return false;
	}
	return true;
}
bool ado::MoveLast()
{
	try
	{
	m_pRecordset->MoveLast();
	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	return false;
	}
	return true;
}
void ado::ExecuteSQL(CString TSQL)
{
	try
	{
	m_pConnection->Execute((_bstr_t)TSQL,NULL,adCmdText);
	}
	catch(_com_error e)
	{
	AfxMessageBox(e.Description());
	
	}
}
void ado::close()
{
//	m_pRecordset->Close();
//	m_pConnection->Close();
//	m_pRecordset=NULL;
//	m_pConnection=NULL;
//	::CoUninitialize();

	//关闭记录集和连接
    if(m_pRecordset!=NULL)
		m_pRecordset->Close();
	m_pConnection->Close();
	//释放环境
	::CoUninitialize();
}
void ado::AddNew()
{
	m_pRecordset->AddNew();
}
void ado::Update()
{
	m_pRecordset->Update();
}
void ado::SetFieldValue(CString OField,CString value)
{_bstr_t tt=value.AllocSysString();
_bstr_t ss=OField.AllocSysString();
	m_pRecordset->PutCollect((_variant_t)ss,(_variant_t)tt);
}
bool ado::recordbof()
{
	if(m_pRecordset->BOF)
	{
		return true;
	}else
	{
		return false;
	}
}
bool ado::recordeof()
{
	if(m_pRecordset->adoEOF)
	{
		return true;
	}else
	{
		return false;
	}
}



void ado::SetTimeValue(CString FileName, COleDateTime MyTime)
{
	_variant_t   vFieldName;   
	_variant_t   vFieldValue;	
	vFieldName.SetString(FileName);   
	vFieldValue.vt = VT_DATE;   
	vFieldValue.date = MyTime;   
   m_pRecordset->put_Collect(vFieldName,   vFieldValue);
}


void ado::SetPicture(CString FileName, CString FilePathName)
{
	CFile f;
	 CFileException e;
	 if(m_Pic.m_IPicture != NULL) m_Pic.FreePictureData(); // Important - Avoid Leaks...


	 
	 if(f.Open(FilePathName, CFile::modeRead | CFile::typeBinary, &e)) //打开了一个jpg文件
	 {	
		 
		 int nSize = f.GetLength();          //先得到jpg文件长度
		 BYTE * pBuffer = new BYTE [nSize];  //按文件的大小在堆上申请一块内存
		 
		 if (f.Read(pBuffer, nSize) > 0 )    //把jpg文件读到pBuffer(堆上申请一块内存)
		 {   // +----------------------------------------------
			 BYTE *pBuf = pBuffer;     ///下面这一大段是把pBuffer里的jpg数据放到库中
			 VARIANT			varBLOB;
			 SAFEARRAY		*psa;
			 SAFEARRAYBOUND	rgsabound[1];
			 
			 //m_pRecordset->AddNew();  
			 
			 if(pBuf)
			 {    
				 rgsabound[0].lLbound = 0;
				 rgsabound[0].cElements = nSize;
				 psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
				 for (long i = 0; i < (long)nSize; i++)
					 SafeArrayPutElement (psa, &i, pBuf++);
				 varBLOB.vt = VT_ARRAY | VT_UI1;
				 varBLOB.parray = psa;
				 m_pRecordset->GetFields()->GetItem(_variant_t(FileName))->AppendChunk(varBLOB);
			 }
			 //m_pRecordset->Update();
			 
			 // +----------------------------------------------
			 
			 
 			 (m_Pic.LoadPictureData(pBuffer, nSize));//接作调用函数读pBuffer的jpg数据准备显示
			 delete [] pBuffer;     //删掉堆上申请的那一块内存
			 pBuf=0;                //以防二次乱用
		 }
		 f.Close();
	 }
	



}


HBITMAP ado::GetPicture(CWnd *p, CString FileName)
{
	HBITMAP m_hBitmap;
	m_hBitmap=NULL;
	//读取图像字段的实际大小
	long lDataSize = m_pRecordset->GetFields()->GetItem(_variant_t(FileName))->ActualSize;
	char *m_pBuffer;  //定义缓冲变量
	if(lDataSize > 0)
	{
		//从图像字段中读取数据到varBLOB中
		_variant_t varBLOB;
		varBLOB = m_pRecordset->GetFields()->GetItem(_variant_t(FileName))->GetChunk(lDataSize);
		if(varBLOB.vt == (VT_ARRAY | VT_UI1))
		{
			if(m_pBuffer = new char[lDataSize+1])	//分配必要的存储空间
			{	
				char *pBuf = NULL;
				SafeArrayAccessData(varBLOB.parray,(void **)&pBuf);
				memcpy(m_pBuffer,pBuf,lDataSize); //复制数据到缓冲区m_pBuffer
				SafeArrayUnaccessData (varBLOB.parray);
				
				//将数据转换为HBITMAP格式
				LPSTR hDIB;
				LPVOID lpDIBBits;
				BITMAPFILEHEADER bmfHeader;  //用于保存BMP文件头信息,包括类型、大小、位移量等
				DWORD bmfHeaderLen;  //保存文件头的长度
				bmfHeaderLen = sizeof(bmfHeader);  //读取文件头的长度
				//将m_pBuffer中文件头复制到bmfHeader中
				strncpy((LPSTR)&bmfHeader, (LPSTR)m_pBuffer, bmfHeaderLen); 	
				if (bmfHeader.bfType != (*(WORD*)"BM"))   //如果文件类型不对,则返回
				{
					AfxMessageBox("BMP文件格式不准确");
					return m_hBitmap;
				}
				hDIB = m_pBuffer + bmfHeaderLen;  //将指针移至文件头后面
				//读取BMP文件的图像数据,包括坐标及颜色格式等信息到BITMAPINFOHEADER对象
				BITMAPINFOHEADER &bmiHeader = *(LPBITMAPINFOHEADER)hDIB;
				//读取BMP文件的图像数据,包括坐标及颜色格式等信息到BITMAPINFO对象
				BITMAPINFO &bmInfo = *(LPBITMAPINFO)hDIB ;
				//根据bfOffBits属性将指针移至文件头后
				lpDIBBits = (m_pBuffer) + ((BITMAPFILEHEADER *)m_pBuffer)->bfOffBits;
				CClientDC dc(p);  //生成一个与当前窗口相关的CClientDC,用于管理输出设置
				//生成DIBitmap数据
				
				m_hBitmap = CreateDIBitmap(dc.m_hDC,&bmiHeader,CBM_INIT,lpDIBBits,&bmInfo,DIB_RGB_COLORS);
			}
		}
	}
	return m_hBitmap;
}

CPicture ado::GetJPG(CWnd *p, CString FileName)
{
	try
	{
		long nSize = m_pRecordset->GetFields()->GetItem(_variant_t(FileName))->ActualSize;
		if(nSize > 0)
		{
			_variant_t	varBLOB;
			varBLOB = m_pRecordset->GetFields()->GetItem(_variant_t(FileName))->GetChunk(nSize);
			if(varBLOB.vt == (VT_ARRAY | VT_UI1))
			{
				if(BYTE *pBuffer = new BYTE [nSize+1])		///重新申请必要的存储空间
				{	
					char *pBuf = NULL;
					SafeArrayAccessData(varBLOB.parray,(void **)&pBuf);
					memcpy(pBuffer,pBuf,nSize);				///复制数据到缓冲区m_pBMPBuffer
					SafeArrayUnaccessData (varBLOB.parray);
					//	int nSize = lDataSize;
					(m_Pic.LoadPictureData(pBuffer, nSize));
					
					delete [] pBuffer;
					pBuf=0;
					
					
					///生成BITMAP对象
					CClientDC dc(p);
					m_Pic.UpdateSizeOnDC(&dc); // Get Picture Dimentions In Pixels
					m_Pic.Show(&dc, CRect(0,50,m_Pic.m_Width,50+m_Pic.m_Height) );
					
	
				}
			}
		}
	}
	catch (_com_error &e)
	{
		e.Description();

	return m_Pic;
	}
	return m_Pic;
}

void ado::SetIntValue(CString FileName, CString MyValue)
{
	
	_variant_t   vFieldName;   
	_variant_t   vFieldValue;	
	vFieldName.SetString(FileName);   
	vFieldValue.vt = VT_I4 ;  //整型数据 
	vFieldValue.intVal =atoi(MyValue);   
   m_pRecordset->put_Collect(vFieldName,   vFieldValue);
}

void ado::SetFloatValue(CString FileName, CString MyValue)
{
 	_variant_t   vFieldName;   
 	_variant_t   vFieldValue;	
 	vFieldName.SetString(FileName);   
 	vFieldValue.vt = VT_R4  ;  //浮点型数据 
 	vFieldValue.fltVal=atof(MyValue);	
    m_pRecordset->put_Collect(vFieldName,   vFieldValue);
}

COleDateTime ado::GetTimeValue(CString FileName)
{
	COleDateTime m_Mytime;
	_variant_t Thevalue;	
    Thevalue=m_pRecordset->GetCollect((_bstr_t)FileName);
	if(Thevalue.vt=VT_DATE)	
	{
		DATE dt=Thevalue.date;
		m_Mytime=COleDateTime(dt);	
		
	}
	return m_Mytime;
}

int ado::GetIntValue(CString FileName)
{
	_variant_t Thevalue;
	CString temp;
	
    Thevalue=m_pRecordset->GetCollect((_bstr_t)FileName);
	if(Thevalue.vt==VT_EMPTY ||Thevalue.vt==VT_NULL)
		temp="";
	else
	{
		temp=(char*)(_bstr_t)Thevalue;
		temp.TrimRight();
		temp.TrimLeft();		
	}
	int m_value;
	m_value=atoi(temp);
	return m_value;
}

float ado::GetFloatValue(CString FileName)
{
	_variant_t Thevalue;
	CString temp;
	
    Thevalue=m_pRecordset->GetCollect((_bstr_t)FileName);
	if(Thevalue.vt==VT_EMPTY ||Thevalue.vt==VT_NULL)
		temp="";
	else
	{
		temp=(char*)(_bstr_t)Thevalue;
		temp.TrimRight();
		temp.TrimLeft();
	}
	float m_value;
	m_value=atof(temp);
	return m_value;
}

long ado::GetLongValue(CString FileName)
{
	_variant_t Thevalue;
	CString temp;
	
    Thevalue=m_pRecordset->GetCollect((_bstr_t)FileName);
	if(Thevalue.vt==VT_EMPTY ||Thevalue.vt==VT_NULL)
		temp="";
	else
	{
		temp=(char*)(_bstr_t)Thevalue;
		temp.TrimRight();
		temp.TrimLeft();
	}
	long m_value;
	m_value=atol(temp);
	return m_value;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -