c++ 连接数据库

 

#include <icrsint.h>
#include<iostream>
#include<iomanip>
#include <string>
using namespace std;
#import "c:\program files\common files\system\ado\msado15.dll"  no_namespace rename("EOF", "adoEOF")
void main()
{
    CoInitialize(NULL);
    _ConnectionPtr  sqlSp;
    HRESULT hr = sqlSp.CreateInstance(_uuidof(Connection));
    if (FAILED(hr))
    {
        cout << "_ConnectionPtr对象指针实例化失败!!!" << endl;
        return;
    }
    else {
        try {
            _bstr_t strConnect = "Driver={sql server};server=127.0.0.1,1433;uid=sa;pwd=123;database=test;";
            sqlSp->Open(strConnect, "", "", adModeUnknown);
        }
        catch (_com_error &e) {
            cout << e.Description() << endl;
        }
        _RecordsetPtr m_pRecordset;
        if (FAILED(m_pRecordset.CreateInstance(_uuidof(Recordset))))
        {
            cout << "记录集对象指针实例化失败!" << endl;
            return;
        }
        try {
            m_pRecordset->Open("select * from  T_test2", (IDispatch*)sqlSp, adOpenDynamic, adLockOptimistic, adCmdText);
        }
        catch (_com_error &e)
        {
            cout << e.Description() << endl;
        }
        try {
            m_pRecordset->MoveFirst();
            while (!m_pRecordset->adoEOF)
            {
                string id = (char*)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("id"))->Value);
                cout << id ; 
                string name = (char*)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("name"))->Value);
                cout << name ;
                string age = (char*)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("age"))->Value);
                cout << age << endl;
                m_pRecordset->MoveNext();
            }
        }
        catch (_com_error &e)
        {
            cout << e.Description() << endl;
        }
    }
    system("pause");
}

 

posted @ 2015-10-25 16:16  微风星宇  阅读(422)  评论(0编辑  收藏  举报