프로그래밍/VC++

VC++에서 ADO 사용하기

panpro 2006. 10. 18. 17:54

1. stdafx.h 파일에 다음을 추가한다.

#pragma warning(push)                         //ado 버그로 인한 컴파일시 경고 뜨는것 방지.
#pragma warning(disable:4146)
#import "C:\\Program Files\\Common Files\\System\\ADO\\msado15.dll" \
rename("EOF", "EndOfFile") no_namespace

//#import "C:\\Program Files\\Common Files\\System\\ADO\\msadox.dll"
#import "C:\Program Files\Common Files\System\ADO\msadox.dll"

#pragma warning(pop)


2. ADO를 사용할 파일에 다음을 include 한다.

#include <comutil.h>


3. 다음 예제를 참조.
// COM인 ADO를 사용하기 위해 CoInitialize 호출
if (FAILED(CoInitialize(NULL)))
{
 return;
}

// Connection String 생성
_bstr_t bstrCon("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\panboy\\rnd\\SystemErrorCode.mdb;Persist Security Info=False");


//---------- ADO관련 처리 시작 ----------//
// ADO Connection 객체 생성
_ConnectionPtr pConnection = NULL;
HRESULT hr = pConnection.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
{
 return;



// ADO 접속
hr = pConnection->Open(bstrCon, L"", L"", -1);
if (FAILED(hr))
{
 return;
}

// 먼저 데이터를 가져온다.
_bstr_t bstrSQL("select ID from SystemErrorCode order by ID");
_RecordsetPtr pRecord("ADODB.Recordset");
_variant_t avarRecords;

hr = pRecord->Open(bstrSQL,_variant_t ((IDispatch*) pConnection, true),
                   adOpenStatic,
                   adLockReadOnly,
                   -1);

if (FAILED(hr))
 return;

int cRecord = 0;
CString str;
int nID;
LPVOID lpMsgBuf;

while(!pRecord->GetEndOfFile())
{
 nID = (int)pRecord->Fields->Item["ID"]->Value;
 str.Format("%d", nID);
 //m_lstbox.AddString(str);
 cRecord++;

 if (!FormatMessage(
  FORMAT_MESSAGE_ALLOCATE_BUFFER |
  FORMAT_MESSAGE_FROM_SYSTEM |
  FORMAT_MESSAGE_IGNORE_INSERTS,
  NULL,
  nID,
  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  (LPTSTR) &lpMsgBuf,
  0,
  NULL ))
 {
  // Handle the error.
  // Display the string.
 
 }
 else
 {
  CString strBuf = (LPCTSTR)lpMsgBuf;
  strBuf.Replace("\r\n", "");
  //::MessageBox( this->m_hWnd, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
 
  bstrSQL = "Update SystemErrorCode set Descript='";
  bstrSQL = bstrSQL + strBuf;
  bstrSQL += "' where ID=";
  bstrSQL = bstrSQL + str;
  try
  {
   hr = pConnection->Execute(bstrSQL, NULL, 0);
  }
  catch (...)
  { 
   //return 0;
  }
 }

 pRecord->MoveNext();  
} // while(!pRecord->GetEndOfFile())

str.Format("총 갯수 : %d", cRecord);
MessageBox(str);


//---------- ADO관련 처리 끝 ----------//