您的位置:首页 > 其它

mfc用ado的方式连接access

2016-11-04 15:22 393 查看
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)
{
CString str1 = _T("");
bRet = finder.FindNextFile();
//查找下一个文件
if (strType== _T(""))
str1 = finder.GetFileTitle();
else
str1 = finder.GetFileName();
//获取文件名,格式如:data.ini
str1.MakeUpper();
str2.MakeUpper();
if (str1 == str2)
{
return TRUE;
}
}
return FALSE;

}

4、创建mdb文件

bool CxinjinDlg::CreateMdb(CString strDBName)


// ::CoInitialize(NULL);
HRESULT hr = S_OK; 
CString strMdbConn = _T("");
strMdbConn.Format(_T("Provider='Microsoft.JET.OLEDB.4.0';Data Source='%s';"), strDBName);
try
{
ADOX::_CatalogPtr pCatalog = NULL;
_bstr_t strcnn(strMdbConn);

hr = pCatalog.CreateInstance(__uuidof (ADOX::Catalog));
if (FAILED(hr))
{
_com_issue_error(hr);
}
else
{
pCatalog->Create(_bstr_t(strcnn)); //创建MDB文件 
}

}
catch(_com_error e)
{
_bstr_t bstrDescription(e.Description());
CString strErro=CString(_T("创建ACCEESS数据库出错: ")) 
+ (LPCSTR)e.Description()
+ CString(_T("Create ACCESS DB error: "))
+ (LPCSTR)e.Description();
AfxMessageBox(strErro);
return false;
}
return true;

}

5、查询是否存在表

bool CxinjinDlg::IsTalbeExit()

{
CString strSQL = _T("");
CTime __tCurrent = CTime::GetCurrentTime();
//strSQL.Format(_T("select * from LaserRecoder_%s"), __tCurrent.Format(_T("%Y_%U")));
strSQL.Format(_T("select * from LaserRecoder_%s"), __tCurrent.Format(_T("%Y")));
try 
{
m_pRecordSet->Open(strSQL.GetBuffer(), (IDispatch*)m_pConnection, adOpenDynamic, adLockOptimistic,\
adCmdText);
}
catch(_com_error e)// 

CString str = e.Description();
return false;
}
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
return true;

}

6、创建表

bool CxinjinDlg::CreateTable()

{
CString strSQL = _T("");
_variant_t RecordsAffected;
// strSQL.Format(_T("select * from LaserRecoder_%s"), __tCurrent.Format(_T("%Y_%U")));
strSQL.Format(_T("CREATE TABLE LaserRecoder_%s(ID AUTOINCREMENT(1,1) PRIMARY KEY, ChangedSN TEXT, \
ChangedTime DATETIME,MarkedSN TEXT, MarkedTime DATETIME, ScannerSN TEXT, ScannerTime DATETIME)"), g_strWeek);
try 
{
m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,1);//创建表users
}
catch(_com_error e)// 
{
AfxMessageBox(e.Description());
return false;
}
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
return true;

}

// 插入数据或更新数据

bool CxinjinDlg::InsertSN(CString SN, CString strRecoder, bool bInsert)

{
CString strSQL=_T(""), strResult=_T("");
if (bInsert)
strSQL.Format(_T("insert into LaserRecoder_%s(%sSN, %sTime) values ('%s', now())"), g_strWeek, strRecoder.GetBuffer(), strRecoder.GetBuffer(), SN.GetBuffer());
else
strSQL.Format(_T("update LaserRecoder_%s set %sSN='%s', %sTime=now() where ChangedSN='%s'"), g_strWeek, strRecoder.GetBuffer(), SN.GetBuffer(), strRecoder.GetBuffer(), SN.GetBuffer());
CString logInfo;
logInfo.Format(_T("更新数据:%s"), strSQL);
LOG_TO_FILE(logInfo);
try 
{
m_pRecordSet->Open((_bstr_t)strSQL, (IDispatch*)m_pConnection, adOpenDynamic, adLockOptimistic, adCmdText);
}
catch(_com_error e)// 
{
AfxMessageBox(e.Description());
CString logInfo;
logInfo.Format(_T("更新数据异常:%s..."), e.Description());
LOG_TO_FILE(logInfo);
return false;
}
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
logInfo.Format(_T("更新数据成功..."));
LOG_TO_FILE(logInfo);
return true;

}

bool CxinjinDlg::IsExistSN(CString SN, CString strRecoder)

{
CString strSQL=_T(""), strResult=_T("");
strSQL.Format(_T("select count(*) as [counter] from LaserRecoder_%s where %sSN='%s'"), g_strWeek, strRecoder.GetBuffer(), SN.GetBuffer());
CString logInfo;
logInfo.Format(_T("查询数据:%s"), strSQL);
LOG_TO_FILE(logInfo);
try 
{
m_pRecordSet->Open((_bstr_t)strSQL, (IDispatch*)m_pConnection, adOpenDynamic, adLockOptimistic, adCmdText);
if (!m_pRecordSet->adoEOF)
{
_variant_t temp = m_pRecordSet->Fields->GetItem(_variant_t("counter"))->Value;
strResult = (LPCTSTR)(_bstr_t)(temp.vt == VT_NULL ? _T("") : temp);
}
}
catch(_com_error e)// 
{
AfxMessageBox(e.Description());
CString logInfo;
logInfo.Format(_T("查询异常,结果为:%s"), e.Description());
LOG_TO_FILE(logInfo);
return false;
}
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
logInfo.Format(_T("查询成功,结果为:%s"), strResult);
LOG_TO_FILE(logInfo);

if (strResult == _T("0")) return false;
else return true;

}

// 關閉連接

void CxinjinDlg::DisConn()

{
m_pConnection->Close();

}

bool CxinjinDlg::QueryTable(CStringArray &strList)

{
try
{
m_pRecordSet = m_pConnection->OpenSchema(adSchemaTables);
while (!m_pRecordSet->adoEOF)
{
_bstr_t table_name = m_pRecordSet->Fields->GetItem("TABLE_NAME")->Value;
strList.Add(CString((LPCSTR)table_name));
m_pRecordSet->MoveNext();
}
}
catch (_com_error e)
{
AfxMessageBox(e.Description());
m_pRecordSet->Close();
return false;
}
CString strTableName;
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
return true;

}

void CxinjinDlg::SaveTableToFile(CString tableName, CString path)

{
CString strSQL=_T(""), strResult=_T("");
// 先查询表结构
CString strName[MAX_PATH]={0},strTemp = _T("");
int nNameCount=0;
try
{
m_pRecordSet->Open((LPCTSTR)tableName, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdTable);
FieldsPtr fds = m_pRecordSet->GetFields();
nNameCount = fds->GetCount();
for (int i = 0; i < nNameCount; i++)
{
FieldPtr fd = fds->GetItem(_variant_t(short(i)));  
if(fd->Value.vt != NULL) 
{
strName[i] = (LPCTSTR)fd->GetName();
strTemp +=strName[i];
if (i != nNameCount-1) strTemp += ",";
}
}
strTemp += "\n";
}
catch(_com_error e)// 
{
AfxMessageBox(e.Description());
m_pRecordSet->Close();
return;
}
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
CStdioFile File;
if (!File.Open(path, CFile::modeCreate | CFile::modeReadWrite | CFile::typeText))
return;
File.SeekToEnd();
File.WriteString(strTemp);
// 再查询数据写入数据
strSQL.Format(_T("select * from LaserRecoder_%s"), g_strWeek);
CString logInfo;
logInfo.Format(_T("查询数据:%s"), strSQL);
LOG_TO_FILE(logInfo);

try 
{
m_pRecordSet->Open((_bstr_t)strSQL, (IDispatch*)m_pConnection, adOpenDynamic, adLockOptimistic, adCmdText);
while (!m_pRecordSet->adoEOF)
{
strTemp = "";
for (int i = 0; i < nNameCount; i++)
{
_variant_t temp = m_pRecordSet->Fields->GetItem(_variant_t(strName[i]))->Value;
strResult = (LPCTSTR)(_bstr_t)(temp.vt == VT_NULL ? "" : temp);
strTemp += strResult;
if (i != nNameCount-1) strTemp += ",";
}
strTemp += "\n";
File.WriteString(strTemp);
m_pRecordSet->MoveNext();
}
}
catch(_com_error e)// 
{
AfxMessageBox(e.Description());
CString logInfo;
logInfo.Format(_T("查询异常,结果为:%s"), e.Description());
LOG_TO_FILE(logInfo);
File.Close();
return;
}
File.Close();
if (m_pRecordSet->State)
{
m_pRecordSet->Close();
}
logInfo.Format(_T("查询成功,结果为:%s"), strResult);
LOG_TO_FILE(logInfo);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: