C++访问Access数据库

  1. 将msado15.dll,msado15.tlh,msado15.tli三个文件放到与代码同一目录下。
  2. 将以下两句代码放到stdafx.h中

#import "msado15.dll" rename("EOF", "adoEOF")
using namespace ADODB;

    3. 连接Access数据库

TCHAR sDrive[_MAX_DRIVE];
TCHAR sDir[_MAX_DIR];
TCHAR sFilename[_MAX_FNAME],sAppFilename[_MAX_FNAME];
TCHAR sExt[_MAX_EXT];
GetModuleFileName(AfxGetInstanceHandle(), sAppFilename, _MAX_PATH);	// 本程序文件名(含路径)
_tsplitpath(sAppFilename, sDrive, sDir, sFilename, sExt);
CString strHomeDir = CString(sDrive) + CString(sDir);
if(strHomeDir.Right(1) != _T("\\") ) strHomeDir += _T("\\");
CString strAppIni = strHomeDir;
pathname = strAppIni;
CString strDbFile = pathname + _T("Database.mdb");
CString strSQL;
HRESULT hr;
try
{
    hr = m_pconnection.CreateInstance(_T("ADODB.Connection"));
    if (SUCCEEDED(hr))
    {
	strSQL.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Persist Security Info=False;Jet OLEDB:DataBase Password=foodexam", strDbFile);
	hr = m_pconnection->Open((_bstr_t)strSQL,"","",adModeUnknown);
    }
}
catch(_com_error e)	// 捕捉异常
{
    CString str = _T("数据库连接错误");
    AfxMessageBox(str);
    return FALSE; 
} 

4. 从数据库中获取数据

try
{
    m_pRcordset.CreateInstance("ADODB.Recordset");	
    m_pRcordset->Open(_variant_t("SELECT * FROM HotFenguangguangdu_Database"), _variant_t((IDispatch*)m_pconnection,true), adOpenStatic, adLockOptimistic, adCmdText);	
    if( m_pRcordset->BOF )
    {
	m_pRcordset->Close();
	m_pRcordset=NULL;
	return FALSE;
    }
    _variant_t  id_namber,test_item,time,sample_name,food_Variety,food_name,Product_trademarks;
    _variant_t Product_batch,Product_specifications,Production_enterprises,By_sampling_enterprise;
    _variant_t Content,Standard_limit,According_standard,Determination,Dilution_ratio,Detecting_unit;
    _variant_t chouyang_data;
    while (!m_pRcordset->adoEOF)
    {
	id_namber = m_pRcordset->GetCollect(_T("ID"));
	test_item = m_pRcordset->GetCollect(_T("检测项目"));
	time = m_pRcordset->GetCollect(_T("时间"));
	sample_name = m_pRcordset->GetCollect(_T("样品名称"));
	food_Variety = m_pRcordset->GetCollect(_T("食物种类"));
	food_name = m_pRcordset->GetCollect(_T("食物名称"));
	Product_trademarks = m_pRcordset->GetCollect(_T("产品商标"));
	Product_batch = m_pRcordset->GetCollect(_T("产品批次"));
	Product_specifications = m_pRcordset->GetCollect(_T("产品规格"));
	Production_enterprises = m_pRcordset->GetCollect(_T("生产企业"));
	By_sampling_enterprise = m_pRcordset->GetCollect(_T("被抽检企业"));
	Content = m_pRcordset->GetCollect(_T("含量"));
	Standard_limit = m_pRcordset->GetCollect(_T("标准限量"));
	Determination = m_pRcordset->GetCollect(_T("结果判定"));
	Dilution_ratio = m_pRcordset->GetCollect(_T("稀释倍数"));
	Detecting_unit = m_pRcordset->GetCollect(_T("检测单位"));  
	chouyang_data  = m_pRcordset->GetCollect(_T("抽样时间"));  
        m_pRcordset->MoveNext();
    }
}
catch(_com_error e)	// 捕捉异常
{
    AfxMessageBox(_T("记录打开错误"));
} 




    



你可能感兴趣的:(C++访问Access数据库)