MFC使用ADO连接数据库的类。

MFC使用ADO连接数据库的类下面是代码

#include "StdAfx.h"

#include "ADOConnect.h"

//////////////////////////////////////////////////////////////////////
// StdAfx.h中加入 #import "E:\vs2008\BuildNcProgram\BuildNcProgram\dll\msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF") //导入ADO动态连接库
// 
//////////////////////////////////////////////////////////////////////
CAdoConnect::CAdoConnect(const CString& szConnectStr)
:m_szConnectStr(szConnectStr)
, m_szServer(_T(""))
, m_szDATABASE(_T(""))
, m_szUID(_T(""))
, m_szPWD(_T(""))
, m_nPort(1433)
{
    ::CoInitialize(NULL);    //初始化OLE/COM库环境
}
CAdoConnect::CAdoConnect(const CString& Server
    , const CString& DATABASE
    , const CString& UID
    , const CString& PWD
    , const int nPort
    )
    : m_szServer(Server)
    , m_szDATABASE(DATABASE)
    , m_szUID(UID)
    , m_szPWD(PWD)
    , m_szConnectStr(_T(""))
    , m_nPort(nPort)
{
    m_szConnectStr.Empty();
    ::CoInitialize(NULL);    //初始化OLE/COM库环境
}


CAdoConnect::~CAdoConnect(void)
{
    //关闭记录集和连接
    if (m_pRecordset != NULL)
    {
        if (m_pRecordset->GetState() == adStateOpen)
        {
            m_pRecordset->Close();
        }
        if (m_pRecordset)
        {
            m_pRecordset.Release();
            m_pRecordset = NULL;
        }
    }


    if (m_pConnection != NULL)
    {
        if (m_pConnection->GetState() == adStateOpen)
        {
            m_pConnection->Close();
        }
        m_pConnection.Release();
        m_pConnection = NULL;
    }

    ::CoUninitialize();    //释放程序占用的COM资源
}

// 连接数据库
BOOL CAdoConnect::OnInitAdoConnection(void)
{
    try
    {
        HRESULT hr = m_pConnection.CreateInstance("ADODB.Connection");//创建Connection 对象
        if (SUCCEEDED(hr))
        {
            m_pConnection->CursorLocation = adUseServer;

            // "Provider=SQLOLEDB.1;Server=数据库IP地址;UID=sa;PWD=你的sa登陆密码;DATABASE=数据库名称;";
            //_bstr_t strConnect = "driver={SQL Server};Server=192.168.0.117;DATABASE=TEST;UID=uid;PWD=passward;";                    
            CString szStr;
            if (m_szConnectStr.IsEmpty())
            {
                szStr.Format(_T("driver={SQL Server};Server=%s,%d;DATABASE=%s;UID=%s;PWD=%s;")
                    , m_szServer, m_nPort, m_szDATABASE, m_szUID, m_szPWD);
            }
            else
            {
                szStr = m_szConnectStr;// = "driver={SQL Server};Server=localhost;DATABASE=EOSDB;UID=sa;PWD=12345;";
            }
            //szStr = m_szConnectStr = "driver={SQL Server};Server=127.0.0.1,1433;DATABASE=EOSDB;UID=sa;PWD=12345;";

            _bstr_t strConnect = szStr;
            // "driver={SQL Server};Server=数据库IP地址;DATABASE=数据库名称;UID=sa;PWD=你的sa登陆密码;";
            HRESULT hr = m_pConnection->Open(strConnect, "", "", adModeUnknown);
            if (SUCCEEDED(hr))
            {
                return TRUE;
            }
            else
            {
                AfxMessageBox("建立数据库连接失败!");
                return FALSE;
            }
        }
    }
    catch (_com_error e)
    {
        AfxMessageBox(e.Description());//显示错误信息
        return FALSE;
    }
    catch (...)
    {
        return FALSE;
    }

    return TRUE;
}

// 执行Insert UpDate
BOOL CAdoConnect::ExecuteSQL(_bstr_t bstrSQL, long lOptions)
{
    try
    {
        //是否已经连接到数据库
        if (m_pConnection == NULL)
        {
            OnInitAdoConnection();
        }
        m_pRecordset = m_pConnection->Execute(bstrSQL, NULL, lOptions);
        return TRUE;
    }
    catch (_com_error e)
    {
        AfxMessageBox(e.Description());
        return FALSE;
    }
    catch (...)
    {
        return FALSE;
    }
}


//执行查询
_RecordsetPtr& CAdoConnect::GetRecordSet(_bstr_t bstrSQL)
{
    try
    {
        //连接数据库 如果Connection对象为空则重新连接数据库
        if (m_pConnection == NULL)
        {
            OnInitAdoConnection();
        }
        //创建记录集对象
        HRESULT hr = m_pRecordset.CreateInstance(__uuidof(Recordset));
        //取得表中的记录
        if (SUCCEEDED(hr))
        {
            m_pRecordset->Open(bstrSQL, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
        }
    }
    catch (_com_error e)
    {
        //异常 显示错误信息
        AfxMessageBox(e.Description());
    }
    return m_pRecordset;
}#pragma once
//#import "E:\vs2008\BuildNcProgram\BuildNcProgram\dll\msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF") //导入ADO动态连接库
#import "c:\Program Files\Common Files\System\ado\msado15.dll"no_namespace \
    rename("EOF", "adoEOF")rename("BOF", "adoBOF")
class CAdoConnect
{
private:
    CString m_szConnectStr;
    CString m_szServer;
    CString m_szDATABASE;
    CString m_szUID;
    CString m_szPWD;
    int m_nPort;
private:
    _ConnectionPtr m_pConnection;     // 连接对象指针
    _RecordsetPtr  m_pRecordset;      // 记录集对象指针

public:
    CAdoConnect(const CString& szConnectStr);
    CAdoConnect(const CString& Server
        , const CString& DATABASE
        , const CString& UID
        , const CString& PWD
        , const int nPort = 1433
        );
    virtual~CAdoConnect(void);

public:
    // 连接数据库
    BOOL OnInitAdoConnection(void);
    // 执行Insert UpDate
    BOOL ExecuteSQL(_bstr_t bstrSQL, long lOptions = adCmdText);
    // 执行查询得到记录集
    _RecordsetPtr& GetRecordSet(_bstr_t bstrSQL);

    // 操作符重载
public:
    _RecordsetPtr& operator->()
    {
        return m_pRecordset;
    }
};

转载请注明来源:http://blog.csdn.net/defaultbyzt

你可能感兴趣的:(数据库,MFC)