废话不多说,自己项目的一点总结:
1、导入msado15.dll
在stdafx.h中导入:
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF") rename("BOF","adoBOF")
2、初始化ADO
在非窗口类的.cpp文件的InitInstance()函数中,加入ADO初始化函数
AfxOleInit(); //初始化COM库
也可以在连接数据库代码前使用另一对函数进行初始化,稍后添加...
2、在程序启动时连接数据库
你可以在OnCreate()函数中连接,也可以类的构造函数中连接,代码:
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->Open("Provider=SQLOLEDB;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=Product;Data Source=192.168.88.95\\SQLEXPRESS","","",adModeUnknown);
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format(_T("连接数据库失败!/r错误信息:%s"),e.ErrorMessage());
AfxMessageBox(errormessage);
return;
}
m_pConnection是全局变量,在类的.h文件中定义:
public:
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
HRESULT hr;