2021-1-15VC++ 如何通过ADO方式访问Access数据库?

19 篇文章 1 订阅
这篇博客详细介绍了如何使用ADO对象进行数据库操作,包括连接ACCESS2000数据库,读取整张表并显示在GridCtrl控件,删除TableData表中的所有记录,以及通过两种方法新增数据到TableData表。
摘要由CSDN通过智能技术生成

1:导入环境

stdafx.h

#import "C:\\Program Files\\Common Files\\System\\ADO\\msado15.dll" rename_namespace("ADOCG") rename("EOF","adoEOF") //rename("BOF","adoBOF") no_namespace
using namespace ADOCG;

 

   _ConnectionPtr m_ptrConnection;//数据库对象    
    _RecordsetPtr    m_ptrRecordset;   //声明记录集指针

    m_ptrConnection.CreateInstance("ADODB.Connection");
    try   
    {   
        m_ptrConnection->ConnectionTimeout = 3;
         //连接ACCESS2000   
        CString strConnect;
        strConnect=_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=")+_T("C:\\TableData.mdb");
        _bstr_t bstrsql;
        bstrsql=(_bstr_t)strConnect;
         m_ptrConnection->Open(bstrsql,"","",adModeUnknown);   

   }   
    catch(_com_error e)
    {   
        CString errormessage;
        errormessage.Format(_T("连接数据库失败!rn错误信息:%s"),e.ErrorMessage());
        AfxMessageBox(errormessage);///显示错误信息
    }   

 

 

2:读取数据库

将整张表显示在GridCtrl控件中

try
    {
        _RecordsetPtr    m_ptrRecordset;   //声明记录集指针
        m_ptrRecordset.CreateInstance(__uuidof(Recordset)); //创建实例

        //读取数据库:
        _bstr_t bstrsql;
        bstrsql="select * from TableData";
        HRESULT hr = m_ptrRecordset->Open(bstrsql, m_ptrConnection.GetInterfacePtr(),adOpenDynamic, adLockPessimistic, adCmdText);


        Fields* fields=NULL;
        long countl;
        BSTR bstr;
        m_ptrRecordset->get_Fields(&fields);
        countl = fields->Count;
        MaxCol=countl;
        int cnt=0;
        for(long i=0;i<countl;i++)
        {
            fields->Item[i]->get_Name(&bstr);
            CString colname=(CString)bstr;
            if (colname==ColNames.GetAt(i))
            {
                m_Grid.InsertColumn(i,colname,LVCFMT_LEFT,100,0);
            
            }
            else
            {
                m_Grid.InsertColumn(i,colname,LVCFMT_LEFT,1,0);
            }
                cnt++;
        }
        fields->Release();

        showCols=cnt;

        int j=0;
        while(!m_ptrRecordset->adoEOF)
        {

            //循环一直读取每一行数据
            m_Grid.InsertItem(j,0);

            for (int i=0;i<cnt;i++)
            {
                LVCOLUMN lvcol;
                TCHAR     lpBuffer[256];
                lvcol.mask = LVCF_TEXT|LVCF_SUBITEM;
                lvcol.pszText =lpBuffer;
                lvcol.cchTextMax = 256;
                m_Grid.GetColumn(i, &lvcol);

                CString strName= lvcol.pszText;

                _variant_t var = m_ptrRecordset->GetCollect((_bstr_t)strName);
                if(var.vt != VT_NULL)
                {    
                    strName = (LPCSTR)_bstr_t(var);
                }
                else
                {
                    strName=_T("");
                }

                m_Grid.SetItemText(j,i,strName);
            }
            j++;
            m_ptrRecordset->MoveNext();/// 移到下一条记录
        }

        if (m_ptrRecordset!=NULL)
        {
            m_ptrRecordset->Close();
            m_ptrRecordset=NULL;
        }
    }
    catch (_com_error* e)
    {
        AfxMessageBox(e->Description());   
    }

3:删除数据库

_bstr_t bstrsql="delete from TableData";
    try
    {
        _variant_t RecordsAffected;
        m_ptrConnection->Execute(bstrsql,&RecordsAffected,adCmdText);
    }
    catch (_com_error* e)
    {
        AfxMessageBox(e->Description());   
    }

4:新增数据

方法1:
        bstrsql="select * from TableData";
        m_ptrRecordset.CreateInstance(__uuidof(Recordset));  //创建记录集对象实例
        m_ptrRecordset->Open(bstrsql, m_ptrConnection.GetInterfacePtr(),adOpenDynamic, adLockPessimistic, adCmdText);
    
        try
        {
            m_ptrRecordset->AddNew();       //添加新行
            //向数据库中插入数据
            CString strKey;
            CString strText;
            //ID
            strKey=_T("ID");
            strText=_T("1");       
            m_ptrRecordset->PutCollect(( _variant_t)strKey,(_variant_t)strText);
            //Name
            strKey=_T("Name");
            strText=_T("xiaoli");             
            m_ptrRecordset->PutCollect(( _variant_t)strKey,(_variant_t)strText);
            //Length
            strKey=_T("Age");
            strText=_T("20");         
            m_ptrRecordset->PutCollect(( _variant_t)strKey,(_variant_t)strText);

            //Image1
            strKey=_T("Image1");
            strText=m_strPicturePath1;
            m_ptrRecordset->PutCollect(( _variant_t)strKey,(_variant_t)strText);
            //Image2
            strKey=_T("Image2");
            strText=m_strPicturePath2;
            m_ptrRecordset->PutCollect(( _variant_t)strKey,(_variant_t)strText);
            
            m_ptrRecordset->Update();       //更新数据表记录
            
            if (m_ptrRecordset!=NULL)
            {
                    m_ptrRecordset->Close();        //关闭记录集
                    m_ptrRecordset=NULL;
            }
        
        }
        catch (...)            //捕捉可能出现的错误
        {
            AfxMessageBox(_T("操作失败"));        //弹出错误提示
            return;
        }

方法2:

CString sql;

  sql = ("insert into TableData(ID, Name,Age,Image1,Image2) values('2','XiaoMei','22','C:\\123.bmp','C:\\1234.bmp') ;  //添加变量到数据库
   try
   {
               m_pConnection->Execute((_bstr_t)sql,NULL, adCmdText);
   }
   catch(_com_error e)
   {
        CString errormessage;
       errormessage.Format("失败!\r\n错误信息:%s",e.ErrorMessage());
        AfxMessageBox(errormessage);///显示错误信息
   }
    
   

// shujukuDlg.cpp : implementation file // #include "stdafx.h" #include "shujuku.h" #include "shujukuDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CShujukuDlg dialog CShujukuDlg::CShujukuDlg(CWnd* pParent /*=NULL*/) : CDialog(CShujukuDlg::IDD, pParent) { //{{AFX_DATA_INIT(CShujukuDlg) m_shuju = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CShujukuDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CShujukuDlg) DDX_Text(pDX, IDC_EDIT1, m_shuju); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CShujukuDlg, CDialog) //{{AFX_MSG_MAP(CShujukuDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_TIMER() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CShujukuDlg message handlers BOOL CShujukuDlg::OnInitDialog() { CDial
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值