void CDBDlg::OnButtonOpen()
{
// TODO: Add your control notification handler code here
//建立一個對話框,選擇mdb文件
static char BASED_CODE szFilter[] = "mbd文件 (*.mdb)|*.mdb|所有文件 (*.*)|*.*||";
char Buffer[MAX_PATH];
::GetCurrentDirectory(MAX_PATH,Buffer);
CFileDialog FileDlg( TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter,NULL );
FileDlg.m_ofn.lpstrInitialDir=Buffer;
if(IDOK==FileDlg.DoModal())
{
lpstrName=FileDlg.GetPathName();
}
//連接數據庫
_bstr_t strcnn(_T("Provider=Microsoft.JET.OLEDB.4.0;Data source=lpstrName"));
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->Open(strcnn,_T(""),_T(""),adModeUnknown);
m_pRecordset.CreateInstance(__uuidof(Recordset));
}
catch (_com_error e)
{
AfxMessageBox("連接數據庫失敗");
return;
}
//打開數據庫
try
{
_bstr_t bstrSQL="SELECT * FROM defects ";//order by RecordNum desc";
m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
while(!m_pRecordset->adoEOF)
{ m_Grid.InsertItem(0,"");
m_Grid.SetItemText(0,0,(char*)(_bstr_t)m_pRecordset->GetCollect("valid"));
m_Grid.SetItemText(0,1,(char*)(_bstr_t)m_pRecordset->GetCollect("maxpost"));
m_Grid.SetItemText(0,2,(char*)(_bstr_t)m_pRecordset->GetCollect("maxminor"));
m_Grid.SetItemText(0,3,(char*)(_bstr_t)m_pRecordset->GetCollect("defecttype"));
m_Grid.SetItemText(0,4,(char*)(_bstr_t)m_pRecordset->GetCollect("maxval1"));
m_Grid.SetItemText(0,5,(char*)(_bstr_t)m_pRecordset->GetCollect("length"));
m_Grid.SetItemText(0,6,(char*)(_bstr_t)m_pRecordset->GetCollect("defectclass"));
m_Grid.SetItemText(0,7,(char*)(_bstr_t)m_pRecordset->GetCollect("tbce"));
m_Grid.SetItemText(0,8,(char*)(_bstr_t)m_pRecordset->GetCollect("speedatmaxval"));
m_Grid.SetItemText(0,9,(char*)(_bstr_t)m_pRecordset->GetCollect("postedspd"));
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
}
catch (_com_error e)
{
AfxMessageBox("數據庫打開失敗");
}
}
你那樣寫根本不會將文件名拼接在連接字符串裡
CString dd;
dd.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",lpstrName);
hr = m_pConnect->Open((_bstr_t)dd,"","",adModeUnknown);
具體:
http://www.cnblogs.com/cy163/archive/2007/04/05/700596.html