用ADO连接Access出错。

追求自由 2004-10-21 05:31:17
void CmfcAdoView::ConnDatabase(){
//AfxEnableControlContainer();
//AfxOleInit();///初始化COM库
////////////连接数据库//////////////
if (!AfxOleInit())
{
AfxMessageBox("初始化OLE失败!");
}


HRESULT hr;
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
_CommandPtr pCommand;

m_pConnection.CreateInstance("ADODB.Connection");
m_pRecordset.CreateInstance("ADODB.Recordset");


try
{

hr = m_pConnection.CreateInstance("ADODB.Connection"); //创建Connection对象

if(SUCCEEDED(hr))
{
//hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\test.mdb","","",adModeUnknown); //连接数据库,用这一句也出错。
hr = m_pConnection->Open("Provider=MADASQL;DSN=test;UID=;PWD=;","","",adModeUnknown);
}
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);

}
m_pRecordset.CreateInstance(__uuidof(Recordset));

try
{
m_pRecordset->Open("SELECT * FROM student", // 查询test表中所有字段
m_pConnection.GetInterfacePtr(), adOpenDynamic,
adLockOptimistic,adCmdText);
}
catch(_com_error e)
{
AfxMessageBox("读取数据库失败!");
}

_variant_t var;
CString strName,strAge;
try
{

if(!m_pRecordset->BOF)
m_pRecordset->MoveFirst();
else
{
AfxMessageBox("表内数据为空");
return;
}

// 读入库中各字段
while(!m_pRecordset->adoEOF)
{

var = m_pRecordset->GetCollect("id");
if(var.vt != VT_NULL)
strName = (LPCSTR)_bstr_t(var);
var = m_pRecordset->GetCollect("name");
if(var.vt != VT_NULL)
strAge = (LPCSTR)_bstr_t(var);
AfxMessageBox("hello:"+strName+":"+strAge);

}

}

catch(_com_error e)
{
AfxMessageBox("读取数据库失败!");
}
}
============================================================
执行到AfxOleInit()时出现:
debug assertion failed.
一看原来是oleinit.cpp里面的ASSERT(!pState->m_bNeedTerm); // calling it twice?
这一行出错了。
接着向下走,就出现了数据库连接错误,数据库打开错误等错误。

...全文
153 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
追求自由 2004-10-22
  • 打赏
  • 举报
回复
bohut说的太正确的。
楼上的也说了一个方面,因为我用的MFC,在app的InitInstance()里已经初始化OLE库了,所以
if (!AfxOleInit())
{
AfxMessageBox("初始化OLE失败!");
}
是多余的。
bohut 2004-10-22
  • 打赏
  • 举报
回复
//hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\test.mdb","","",adModeUnknown);

改成:

//hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test.mdb","","",adModeUnknown);
kugou123 2004-10-21
  • 打赏
  • 举报
回复
重复调用可能会出错。
内存泄漏 2004-10-21
  • 打赏
  • 举报
回复
不用AfxOleInit();换用下面的语句试试看:

CoInitialize(NULL);
注意代码的最后要调用CoUninitialize();
BombZhang 2004-10-21
  • 打赏
  • 举报
回复
是不是之前已经调用过AfxOleInit()了?

4,017

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 数据库
社区管理员
  • 数据库
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧