用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?
这一行出错了。
接着向下走,就出现了数据库连接错误,数据库打开错误等错误。