VC6.0中DAO与ADO技术

来源:互联网 发布:互联网用户数据分析 编辑:程序博客网 时间:2024/06/06 03:33

DAO:
 #include <afxdao.h>
 
 CDaoDatabase m_DB;     
 CDaoRecordset rst;
 
 ::AfxGetModuleState()->m_dwVersion=0x601;
 ::AfxDaoInit();
 
 if(!fDirectory)
 {
  ::GetCurrentDirectory(80,p);
  strcat(p,"//State.mdb"); 
  fDirectory = true;
 }

 try
 {
  m_DB.Open(p,false,false,"ms access");
 }
 catch(CDaoException*)
 {
  ::MessageBox(NULL,"打开数据文件错误!","错误",MB_OK|MB_ICONERROR);
  return;
 }
 
 COleVariant var;
 rst.m_pDatabase = &m_DB;
 try
 {
  rst.Open(AFX_DAO_USE_DEFAULT_TYPE,strSql);
  if(rst.GetFieldCount!=0)
  {
   rst.Edit();
   rst.SetFieldValue("ResponseLamp",(LPCTSTR)strState);
   rst.Update();
   // 获取Mark列值
   rst.GetFieldValue("Mark",var); 
   strMark = (const char*)var.pbVal;
  }
 }
 catch(CDaoException*)
 {
  rst.Close();
  m_DB.Close();
  AfxMessageBox("修改设备操作盘回答灯状态时出错!");
  return;
 }
 rst.Close();
 m_DB.Close();
 
ADO:
 StdAfx.h 最后一个#endif前加
 #import "E:/program files/common files/System/ado/msado15.dll" no_namespace rename("EOF","adoEOF")  
 
 BOOL CXXXApp::InitInstance()里
 if(!AfxOleInit()) //初始化COM库
 {
  AfxMessageBox("OLE初始化出错!");
  return false;
 }
 
 CoInitialize(NULL);
 // TODO: Add extra initialization here
 try
 {
//  ADOConn.CreateInstance(_uuidof(Connection));
  ADOConn.CreateInstance("adodb.connection");
  rst.CreateInstance(_uuidof(Recordset));

  // 连接ACCESS
  ADOConn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c://Temp.mdb","","",adModeUnknown);

  // 连接SQL Server2005
//  ADOConn->Open("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Temp;Data Source=XFW-HUANGHE","","",adModeUnknown);
 }
 catch(_com_error &e)
 {
  CString err;
  err.Format("连接数据库失败!/r/n错误信息:%s", e.ErrorMessage() );
  AfxMessageBox(err);
  return false;
 }
 
 try
 {
  _variant_t varValue;
  CString strSql,strValue;
  strSql = "select * from T_User";
  rst = ADOConn->Execute((_bstr_t)strSql,NULL,adCmdText);
  //查询
//  varValue = rst->GetFields()->GetItem((long)0)->Value;
  varValue = rst->GetCollect("user_name");
  //添加
  /*
  rst->AddNew();
  rst->GetFields()->GetItem((long)0)->Value=L"YP00100";
  rst->PutCollect("user_id",_variant_t(long)3);
  ...
  rst->Update();
  */
  //修改
  //_bstr_t bstrValue = "NewData";
  // rst->GetFields()->GetItem((long)i)->Value = bstrValue;
  //删除
  //rst->Delete(adAffectCurrent);
  strValue = (char*)(_bstr_t)varValue;                          

  AfxMessageBox(strValue);
//  rst->Close();
//  ADOConn->Close();
 }
 catch(_com_error &e)
 {
  CString strError;
  strError.Format("连接数据库失败!/r/n错误信息:%s", e.ErrorMessage());
  AfxMessageBox(strError);
 }