1、包含头文件,导入dll
// ado
#include <atlbase.h>#import "MSADOX.dll"
#import "MSADO15.dll" no_namespace rename("EOF", "adoEOF")
#define TESTHR(x) if FAILED(x) _com_issue_error(x);
#define TEXT_CHANGED _T("Changed")
#define TEXT_MARKED _T("Marked")
#define TEXT_SCANNER _T("Scanner")
2、初始化
bool CxinjinDlg::InitConn(CString strFileNeme){
::CoInitialize(NULL);
CTime __tCurrent = CTime::GetCurrentTime();
/*g_strWeek = __tCurrent.Format("%Y_%U");*/
g_strWeek = __tCurrent.Format("%Y");
if (!IsExistFile(strFileNeme, _T("mdb"))) // 如果数据库不存在则需要打开连接
{
if (!CreateMdb(GetAbsolutePathName(strFileNeme))) return false;
}
HRESULT hr = m_pConnection.CreateInstance(_uuidof(Connection));
if(FAILED(hr))
{
AfxMessageBox(_T("_ConnectionPtr對象指針實例化失敗"));
return false;
}
try
{
CString strConnect = _T("");
strConnect.Format(_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='%s'"), GetAbsolutePathName(strFileNeme));
m_pConnection->Open(strConnect.GetBuffer(),"","",adModeUnknown);
}
catch(_com_error &e)
{
AfxMessageBox(e.Description());
// if (CreateMdb(databasepath)) return InitConn(databasepath);
return false;
}
m_pRecordSet.CreateInstance(_uuidof(Recordset));
if (!IsTalbeExit())
return CreateTable();
return true;
}
3、IsExistFile判断mdb文件是否存在
BOOL CxinjinDlg::IsExistFile(CString strFileName, CString strType, CString strFolder)
{
CString strPath = strFolder==_T("")?GetAbsolutePathName(_T("")):strFolder, str2 = _T("");
strPath += _T("\\*.");
strPath += strType==_T("")?_T("*"):strType;
CFileFind finder;
BOOL bRet = finder.FindFile(strPath);
if (!bRet) return FALSE;
if (strType==_T(""))
str2.Format(_T("%s"), strFileName);
else
{
if (strFileName.Find('.')) str2 = strFileName;
else str2.Format(_T("%s.%s"), strFileName,strType);
}
while (bRet)
{