C++连接access数据库

2017-09-23  本文已影响0人  zjh3029
#include <iostream>  
using namespace std;

#import "c:\program files\common files\system\ado\msado15.dll"  no_namespace  rename ("EOF", "adoEOF")  

void main()
{
    CoInitialize(NULL);         //初始化OLE/COM库环境  
                                //在引入ado并初始化成功com库后,就可以使用智能指针了  
    _ConnectionPtr m_pConnection;
    _RecordsetPtr m_pRecordset;
    HRESULT hr;
    try
    {
        hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象  
                                                              //     hr = m_pConnection.CreateInstance(__uuidof(Connection));//no_namespace的好处  

        if (SUCCEEDED(hr))
        {
            hr = m_pConnection->Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;Persist Security Info=False ", "", "", adModeUnknown);         

            printf("成功连接数据库\n");
        }
    }
    catch (_com_error e)///捕捉异常  
    {
        printf("连接数据库失败!\n");
        return;
    }
    m_pRecordset.CreateInstance(__uuidof(Recordset)); //实例化结果集对象     
                                                      //执行sql语句     
    try
    {
        char sql[300];
        memset(sql, 0, 300);
        strcat_s(sql, "SELECT * FROM status");
        m_pRecordset->Open(sql, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
    }
    catch (_com_error* e)
    {
        cout << (e->ErrorMessage()) << endl;
        if (m_pConnection->State)
        {
            m_pConnection->Close();
            m_pConnection = NULL;
        }
        CoUninitialize();
        return;
    }
    try
    {
        //若结果为空,结束     
        if (m_pRecordset->BOF)
        {
            printf("表内数据为空!");
            if (m_pConnection->State)
            {
                m_pRecordset->Close();
                m_pRecordset = NULL;
                m_pConnection->Close();
                m_pConnection = NULL;
            }
            CoUninitialize();
            return;
        }
        cout << "---------------------------------" << endl;
        cout << "数据库的内容为:" << endl;
        //游标定位到第一条记录  
        m_pRecordset->MoveFirst();
        _variant_t var[2]; //从结果集中取出的数据放到var中  
        char *t1[2];
        while (!m_pRecordset->adoEOF)
        {
            var[0] = m_pRecordset->GetCollect("ID");
            if (var[0].vt != VT_NULL)
            {
                t1[0] = _com_util::ConvertBSTRToString((_bstr_t)var[0]);
            }
            printf(t1[0]);
            printf("\t");
            var[1] = m_pRecordset->GetCollect("姓名");
            if (var[1].vt != VT_NULL)
            {
                t1[1] = _com_util::ConvertBSTRToString((_bstr_t)var[1]);
            }
            printf(t1[1]);
            printf("\n");
            m_pRecordset->MoveNext();
            system("pause");
        }
    }
    catch (_com_error *e)
    {
        cout << e->ErrorMessage() << endl;
    }

    //退出程序时的处理     
    if (m_pConnection->State)
    {
        m_pRecordset->Close();
        m_pRecordset = NULL;
        m_pConnection->Close();
        m_pConnection = NULL;
    }
    CoUninitialize();
    cout << "---------------------------------" << endl;
    return;
}
#include <iostream>  
#include <string>
using namespace std;

#import "c:\program files\common files\system\ado\msado15.dll"  no_namespace  rename ("EOF", "adoEOF")  

class AdoAccess {
public:
    _ConnectionPtr   HX_pConnection; // 数据库指针  
    _RecordsetPtr    HX_pRecordset; // 命令指针  
    _CommandPtr      HX_pCommand; // 记录指针  
    void OnInitADOConn() {
        CoInitialize(NULL);
        try
        {
            HX_pConnection.CreateInstance("ADODB.Connection"); 
            _bstr_t strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;Persist Security Info=False ";
            
            HX_pConnection->Open(strConnect, "", "", adModeUnknown);    //连接数据库  
            cout << "连接成功,并获得智能指针" << endl;
        }
        catch (_com_error e)
        {
            cout << e.Description() << endl;
        }

    }
    void ExitConnect() {
        if (HX_pRecordset != NULL)
            HX_pRecordset->Close();
        HX_pConnection->Close();
        ::CoUninitialize();
    }
};

string access_out(string in_var)
{
    AdoAccess dataBase;
    string out_var;
    //初始化  
    dataBase.OnInitADOConn();
    dataBase.HX_pRecordset.CreateInstance("ADODB.Recordset");


    //选择名为Test的表格  
    dataBase.HX_pRecordset->Open("select *  from status",
        dataBase.HX_pConnection.GetInterfacePtr(),
        adOpenDynamic,
        adLockOptimistic,
        adCmdText);

    int i = 0;
    //读取其中的name字段所有数据,并显示  
    _variant_t var, var1;
    string strValue, strValue1;
    while (!dataBase.HX_pRecordset->adoEOF)
    {
        var = dataBase.HX_pRecordset->GetCollect("input");
        //其他类似,都是通过HX_pRecordset传递SQL语句执行查找、添加、删除等命令  
        var1 = dataBase.HX_pRecordset->GetCollect("output");
        //var1.Attach(var);
        if (var.vt != VT_NULL)
            strValue = _com_util::ConvertBSTRToString((_bstr_t)var);
            strValue1 = _com_util::ConvertBSTRToString((_bstr_t)var1);
        //cin >> strValue;
        if (strValue== in_var)
        {
            out_var = strValue1;
        }
        //cout << "name " << i << "  " << strValue << endl;
        ++i;
        dataBase.HX_pRecordset->MoveNext();
    }
    //卸载com组件  
    dataBase.ExitConnect();
    return out_var;
}

void main()
{
    cout << access_out("我") << endl;
    system("pause");
    return;
}
上一篇下一篇

猜你喜欢

热点阅读