activeconnectionx.cpp

来自「visual c++ 很全的ado的sample」· C++ 代码 · 共 174 行

CPP
174
字号
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
    no_namespace rename("EOF", "EndOfFile")

#define TESTHR(x) if FAILED(x) _com_issue_error(hr)

#include <stdio.h>
#include <ole2.h>
#include "conio.h"
#include "ActiveConnectionX.h"

//Function declaration
void ActiveConnectionX(VOID);
void PrintProviderError(_ConnectionPtr pConnection);

///////////////////////////////////////////////////////////
//                                                       //
//      Main Function                                    //
//                                                       //
///////////////////////////////////////////////////////////
void main()
{
	if(FAILED(::CoInitialize(NULL)))
		return;
	
	ActiveConnectionX();
		
	//Wait here for user to see the output..
	printf("\n\nPress any key to continue..");
	getch();  
	
	::CoUninitialize();
}



///////////////////////////////////////////////////////////
//                                                       //
//      ActiveConnectionX Function                       //
//                                                       //
///////////////////////////////////////////////////////////
VOID ActiveConnectionX(VOID)
{
   HRESULT hr = S_OK;  
	
	// Define ADO object pointers.
    // Initialize pointers on define.
    // These are in the ADODB::  namespace.
   _ConnectionPtr  pConnection      = NULL;
   _CommandPtr     pCmdByRoyalty  = NULL;
   _RecordsetPtr  pRstByRoyalty  = NULL;
   _RecordsetPtr  pRstAuthors   = NULL;
   _ParameterPtr    pPrmByRoyalty  = NULL;


   //Define Other variables
	IADORecordBinding   *picRs = NULL;  //Interface Pointer declared.(VC++ Extensions)  TCS(SPA)
	CEmployeeRs emprs;          //C++ class object  TCS(SPA)
	_bstr_t strAuthorId;
	int intRoyalty;
	VARIANT vtroyal ; 

	_bstr_t strCnn("Provider=sqloledb;Data Source=YourServer;"
			"Initial Catalog=pubs;User Id=sa;Password=;");

try
{
	//Define a command object for a stored procedure. 

	TESTHR(pConnection.CreateInstance(__uuidof(Connection)));      
	hr = pConnection->Open(strCnn,"","",NULL);  
	
	TESTHR(pCmdByRoyalty.CreateInstance(__uuidof(Command)));
	
	pCmdByRoyalty->ActiveConnection = pConnection;
	pCmdByRoyalty->CommandText = "byRoyalty";
	pCmdByRoyalty->CommandType = adCmdStoredProc;
	pCmdByRoyalty->CommandTimeout = 15;

	//Define stored procedure's input parameter. 
	printf("Enter Royalty :  ");
	scanf("%d",&intRoyalty);

	//Assign Integer value 
	vtroyal.vt = VT_I2;
	vtroyal.iVal  = intRoyalty;

	TESTHR(pPrmByRoyalty.CreateInstance(__uuidof(Parameter)));
	pPrmByRoyalty->Type = adInteger;
	pPrmByRoyalty->Size = 3;
	pPrmByRoyalty->Direction = adParamInput;
	pPrmByRoyalty->Value = vtroyal;
	pCmdByRoyalty->Parameters->Append(pPrmByRoyalty);
	
	//Create a recordset by executing a command. 
	pRstByRoyalty = pCmdByRoyalty->Execute(NULL,NULL,adCmdStoredProc); 

	//Open the authors table to get author names for display. 

	TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
	hr = pRstAuthors->Open("authors",strCnn,adOpenForwardOnly,adLockReadOnly,adCmdTable);

	//Open an IADORecordBinding interface pointer which we'll use for Binding Recordset to a class    
	TESTHR(pRstAuthors->QueryInterface(__uuidof(IADORecordBinding),(LPVOID*)&picRs));

	//Bind the Recordset to a C++ Class here    
	TESTHR(picRs->BindToRecordset(&emprs));


	//Print current data in the recordset ,adding author names from author table. 
	printf("Authors With  %d  Percent Royalty",intRoyalty);

	while(!(pRstByRoyalty->EndOfFile))
	{
		strAuthorId = pRstByRoyalty->Fields->Item["au_id"]->Value;
		pRstAuthors->Filter = "au_id = '"+strAuthorId+"'";
	 
		printf("\n\t%s, %s %s",emprs.lau_idStatus == adFldOK ? emprs.m_szau_id : "<NULL>",\
		emprs.lau_fnameStatus == adFldOK ? emprs.m_szau_fname : "<NULL>",\
				emprs.lau_lnameStatus == adFldOK ? emprs.m_szau_lname : "<NULL>");

		pRstByRoyalty->MoveNext(); 
	}
	
	// Clean up objects before exit
	pRstByRoyalty->Close();
	pRstAuthors->Close();

	//Release the IADORecordset Interface here   
	if (picRs)
	    picRs->Release();
	    pConnection->Close(); 
}

catch(_com_error &e)
{
	// Notify the user of errors if any.
	_bstr_t bstrSource(e.Source());
	_bstr_t bstrDescription(e.Description());

	 PrintProviderError(pConnection);
     printf("Source : %s \n Description : %s \n",(LPCSTR)bstrSource,(LPCSTR)bstrDescription);
}

}



///////////////////////////////////////////////////////////
//                                                       //
//      PrintProviderError Function                      //
//                                                       //
///////////////////////////////////////////////////////////

VOID PrintProviderError(_ConnectionPtr pConnection)
{
	// Print Provider Errors from Connection object.
	// pErr is a record object in the Connection's Error collection.
	ErrorPtr    pErr  = NULL;
	long      nCount  = 0;    
	long      i     = 0;

	if( (pConnection->Errors->Count) > 0)
	{
		nCount = pConnection->Errors->Count;
		// Collection ranges from 0 to nCount -1.
		for(i = 0; i < nCount; i++)
		{
			pErr = pConnection->Errors->GetItem(i);
			printf("Error number: %x\t%s", pErr->Number,(LPCSTR)pErr->Description);
		}
	}
}

⌨️ 快捷键说明

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