1.首先建立一个对话框程序
2.将 X:\Program Files\Common Files\System\ado\msado15.dll中的 msado15.dll 复制到工程所在的目录
3.在stdafx.h的文中,在所有的#include后面添加
#import "D:\Users\wan-g\Documents\visual studio 2012\Projects\textADO2\textADO2\msado15.dll"no_namespace \rename("EOF", "adoEOF")
说明:D:\Users\wan-g\Documents\visual studio 2012\Projects\textADO2\textADO2\ 为我的工程所在目录
4。点击调试,然后把Debug目录的msado15.tlh和msdao15.tli添加到该工程
5在对话框的头文件 textADO2Dlg.h 中定义ADO的3大指针
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
_CommandPtr m_pCommandPtr;
6在该头文件的原文件的.cpp中的OnInitDialog()中对指针进行初始化
AfxOleInit(); //com的MFC初始化方式
HRESULT hr;
try
{
hr=m_pConnection.CreateInstance(__uuidof(Connection));
if(SUCCEEDED(hr))
{
m_pConnection->Open(_bstr_t(_T("Provider=MSDASQL.1;Persist Security Info=False;Data Source=WAN-G")), _bstr_t(_T("")), _bstr_t(_T("")), adOpenUnspecified);
}
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format(_T("连接数据库失败!\r\n\错误信息:%s"),e.ErrorMessage());
AfxMessageBox(errormessage);
}
//以上是m_pConnection的初始化方式
m_pRecordset.CreateInstance(__uuidof( Recordset )); //创建实例
m_pRecordset->Open("select * from dbo.学生信息",_variant_t((IDispatch*)m_pConnection),adOpenDynamic,adLockOptimistic,adCmdText);
//以上是m_pRecordset的初始化
m_pCommandPtr.CreateInstance(__uuidof(Command));
m_pCommandPtr->put_ActiveConnection(_variant_t((IDispatch*)m_pConnection));
//以上是m_pCommandPtr的初始化
7初始化完了就可以使用了
<说明>
m_pRecordset //功能为对表指针操作
m_pCommandPtr //功能为执行SQL语句
while (!m_pRecordset->adoEOF)
{
CString STR=m_pRecordset->GetCollect(_T("姓名"));//得到数据 姓名为列
CString STR;
((CListBox*)GetDlgItem(IDC_LIST1))->AddString(STR);
m_pRecordset->MoveNext();
}
//m_pRecordset 的使用
m_pCommandPtr->CommandText=_T("select * from dbo.学生信息"); //SQL语句
m_pRecordset=m_pCommandPtr->Execute(NULL,NULL,adCmdText);//执行SQL语句
while(!m_pRecordset->adoEOF)
{
((CListBox*)GetDlgItem(IDC_LIST1))->AddString(
(_bstr_t)m_pRecordset->GetCollect(_T("姓名")));
m_pRecordset->MoveNext();
}
//使用完了
要记得释放对象
m_pRecordset->Close();
m_pConnection->Close();
m_pCommandPtr.Release();
m_pRecordset.Release();
m_pConnection.Release();
//释放函数对象的顺向一定要按照上面的顺序否则会出错;
总结:该工程是在VC2012的MFC对话框的Unicode 字符集下成功调试运行
比较简单;