zoukankan      html  css  js  c++  java
  • VC连接access


    (1)首先拷贝 c:program filescommon filessystemado 目录中的 msado15.dll 文件到项目中。

    (2)在VC中加入DLL,具体方法如下:



    (3)创建连接对象,和打开数据库的具体代码如下:

    void CMyDlg::OnButton1() 
    {
        // TODO: Add your control notification handler code here
        
        if (AfxOleInit())//初始化OLE
        {
            _ConnectionPtr m_pConnection;//声明一个连接对象
            _RecordsetPtr m_pRecordset;
            HRESULT hr;
            try{
    
                hr = m_pConnection.CreateInstance("ADODB.Connection"); //创建连接
                if(SUCCEEDED(hr))//判断是否连接成功
                {
                    MessageBox("指针连接成功!");
                    m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb","","",adModeUnknown);//打开数据库
                    
                    _variant_t RecordsAffected;//声明返回被修改的条目数
                    CString strSQL;//SQL字符串语句
                    strSQL.Format("insert into d1(name) values('%s')","正月龙");
                    m_pRecordset = m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);//操作数据库
                    MessageBox("数据加入成功!");
                    //m_pRecordset->Close();
                                    
                    
                    m_pRecordset = m_pConnection->Execute("select count(*) from d1",&RecordsAffected,adCmdText);//返回总条目数
                    _variant_t vIndex = (long)0;  
                    _variant_t vCount = m_pRecordset->GetCollect(vIndex);//取得第一个字段的整数值放入vCount变量
                    CString str;
                    str.Format("总共有%d条数据",vCount.lVal);
                    MessageBox(str);
    
    
                    m_pRecordset = m_pConnection->Execute("select * from d1",&RecordsAffected,adCmdText);
                    //m_pRecordset->MoveNext();
                    //m_pRecordset->MoveNext();
                    _variant_t vIndex1 = (long)0;  
                    _variant_t vCount1 = m_pRecordset->GetCollect(vIndex1);//取得第一个字段的字符串值放入vCount1变量 
                    CString str1;
                    str1 = vCount1.bstrVal;
                    MessageBox("第一个字段内容是:"+str1);
    
                    m_pRecordset->Close();
    
                }
            }catch(_com_error e)
            {
                CString str;
                str.Format("数据库连接失败
    错误信息:%s",e.ErrorMessage());
                MessageBox(str);
    
            }
            
            //MessageBox("初始化 OLE 成功!");
        }else
    
    
        MessageBox("初始化 OLE 失败");
        
    }
    
    
    
     
  • 相关阅读:
    我爱java系列之---【微服务间的认证—Feign拦截器】
    我爱java系列之---【设置权限的三种解决方案】
    581. Shortest Unsorted Continuous Subarray
    129. Sum Root to Leaf Numbers
    513. Find Bottom Left Tree Value
    515. Find Largest Value in Each Tree Row
    155. Min Stack max stack Maxpop O(1) 操作
    painting house
    Minimum Adjustment Cost
    k Sum
  • 原文地址:https://www.cnblogs.com/webcyz/p/6525169.html
Copyright © 2011-2022 走看看