首页 > 代码库 > ADO访问Access数据库错误解决

ADO访问Access数据库错误解决

最近在用ADO访问Access数据库的时候出现了一个奇怪的错误,觉得有必要记录下来,和大家分享一下。

环境

win7 x86系统;

VS2012编译器;

Office2010;

Access2000~Access2003连接串建立数据库连接。

关键数据库操作代码

BOOL CAccessDatabase::Query(const CString strSQLString, UINT nFieldNumber, vector<vector<_variant_t> >& vecvecVariant)

{

_variant_t Variant;

vector<_variant_t> vecVariant;

EnterCriticalSection(&m_cs);

_RecordsetPtr pRecordset = NULL;

HRESULT hr = S_FALSE;

try

{

hr = pRecordset.CreateInstance(_T("ADODB.Recordset"));

if (SUCCEEDED(hr))

{

hr = pRecordset->Open(strSQLString.AllocSysString(), m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);

if (SUCCEEDED(hr))

{

if (!pRecordset->adoEOF)

{

hr = pRecordset->MoveFirst();

if (SUCCEEDED(hr))

{

while (!(pRecordset->adoEOF))

{

vecVariant.clear();

for (UINT i = 0; i < nFieldNumber; ++i)

{

ZeroMemory(&Variant, sizeof(Variant));

Variant = pRecordset->GetCollect(_variant_t((long)i));

vecVariant.push_back(Variant);

}

vecvecVariant.push_back(vecVariant);

hr = pRecordset->MoveNext();

}

}

else

{

m_pLogFile->WriteLog(GetLastError(), _T("移动记录集指针到首部发生错误"));

if (pRecordset->GetState() != adStateClosed)

{

hr = pRecordset->Close();

if (FAILED(hr))

{

m_pLogFile->WriteLog(GetLastError(), _T("关闭记录集失败"));

}

else

{

m_pLogFile->WriteLog(GetLastError(), _T("记录集已关闭"));

}

}

if (pRecordset != NULL)

{

pRecordset.Release();

pRecordset = NULL;

}

LeaveCriticalSection(&m_cs);

return FALSE;

}

}

else

{

m_pLogFile->WriteLog(GetLastError(), _T("查询的记录集为空"));

}

}

else

{

m_pLogFile->WriteLog(GetLastError(), _T("打开记录集失败"));

if (pRecordset != NULL)

{

pRecordset.Release();

pRecordset = NULL;

}

LeaveCriticalSection(&m_cs);

return FALSE;

}

}

else

{

m_pLogFile->WriteLog(GetLastError(), _T("初始化记录集失败"));

pRecordset = NULL;

LeaveCriticalSection(&m_cs);

return FALSE;

}

}
catch (_com_error e)

{

m_pLogFile->WriteLog(e.ErrorMessage());

AfxMessageBox(e.ErrorMessage());

LeaveCriticalSection(&m_cs);

return FALSE;

}

if (pRecordset->GetState() != adStateClosed)

{

try

{

hr = pRecordset->Close();

if (FAILED(hr))

{

m_pLogFile->WriteLog(GetLastError(), _T("关闭记录集失败"));

}

else

{

m_pLogFile->WriteLog(GetLastError(), _T("记录集已关闭"));

}

}

catch (_com_error err)

{

m_pLogFile->WriteLog(err.ErrorMessage());

AfxMessageBox(err.ErrorMessage());

}

}

if (pRecordset != NULL)

{

pRecordset.Release();

pRecordset = NULL;

}

LeaveCriticalSection(&m_cs);

return TRUE;

}

数据库调用代码

if (!Database.Query(_T("select ZoneName from Zone"), 1, vecvecZone))

{

LogFile.WriteLog(GetLastError(), _T("从数据库中获取客户端名称失败"));

AfxMessageBox(_T("从数据库中获取客户端名称失败"));托福答案

return;

}

错误问题

程序在Query里面产生了异常。在调用pRecordset->Open(…)的时候产生了异常,异常错误信息是"未指定的错误";

将调用的Sql语句放到Access数据库中可以正确执行。雅思答案

解决办法

将数据库的表名"Zone"修改为"MyZone"等其它名称即可。

总结

在编程访问Access数据库时表名不能为"Zone".

ADO访问Access数据库错误解决