VC++中采用ADO操作SQL数据库

长平狐 发布于 2013/12/25 17:20
阅读 100
收藏 0
// ADOConn.cpp: implementation of the ADOConn class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ADOConn.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

ADOConn::ADOConn()
{
}

ADOConn::~ADOConn()
{
}

void ADOConn::OnInitADOConn()
{
 ::CoInitialize(NULL);
 try
 {
  m_pConnection.CreateInstance("ADODB.Connection");
  _bstr_t strConnection="driver={SQL Server};SERVER=210.45.155.53;UID=sa;PWD=123456;DATABASE=test";
  m_pConnection->Open(strConnection,"","",adModeUnknown);
 }
 catch(_com_error e)
 {
  AfxMessageBox(e.Description());
 }
}

_RecordsetPtr& ADOConn::GetRecordSet(_bstr_t bstrSQL)
{
 try
 {
  if(m_pConnection==NULL)
   OnInitADOConn();
  m_pRecondset.CreateInstance(__uuidof(Recordset));
  m_pRecondset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
 }
 catch (_com_error e)
 {
  e.Description();
  m_pRecondset=NULL;
  throw CString("invalid sql.");
  return m_pRecondset;
 }
 return m_pRecondset;
}

int ADOConn::ExecuteSQL(_bstr_t bstrSQL)
{
 _variant_t RecordsAffected;
 int ret=-1;
 try
 {
  if (m_pConnection==NULL)
   OnInitADOConn();
  m_pConnection->Execute(bstrSQL,&RecordsAffected,adCmdText);
  ret=atoi((LPCSTR)(_bstr_t)RecordsAffected);
  return ret;
 }
 catch (_com_error e)
 {
  e.Description();
  return -1;
 }
}

void ADOConn::ExitConnect()
{
 if (m_pRecondset!=NULL)
  m_pRecondset->Close();
 m_pConnection->Close();
 ::CoUninitialize();
}

原文链接:http://blog.csdn.net/singwhatiwanna/article/details/8857742
加载中
返回顶部
顶部