Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3432961
  • 博文数量: 754
  • 博客积分: 10132
  • 博客等级: 上将
  • 技术积分: 7780
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-14 23:36
文章分类

全部博文(754)

文章存档

2012年(3)

2011年(39)

2010年(66)

2009年(167)

2008年(479)

我的朋友

分类: C/C++

2008-03-04 10:51:53

/*********************
*                    *
*     ADO操作实例     *
*                    *
*********************/
::CoInitialize(NULL);   //初始化OLE/COM库环境  
 
程序最后要调用   ::CoUninitialize();//释放程序占用的COM   资源。

#pragma once
#include "afxwin.h"
#include
using namespace std ;
// CADOSampleDlg 对话框
class CADOSampleDlg : public CDialog
{
 DECLARE_DYNAMIC(CADOSampleDlg)
public:
 CADOSampleDlg(CWnd* pParent = NULL);   // 标准构造函数
 virtual ~CADOSampleDlg();
// 对话框数据
 enum { IDD = IDD_DLG_ADOSAMPLE };
protected:
 virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持
 DECLARE_MESSAGE_MAP()
public:
 // 添加按钮
 CButton m_btnAdd;
public:
 // 修改按钮
 CButton m_btnEdit;
public:
 // 列表按钮
 CButton m_btnList;
public:
 // ID号
 CEdit m_ID;
public:
 // 姓名
 CEdit m_EditStudentName;
public:
 // 出生日期
 CEdit m_EditBirthday;
public:
 // 班级
 CEdit m_EditGrade;
public:
 // 列表
 CEdit m_EditList;
public:
 afx_msg void OnBnClickedBtnAdd();
public:
 afx_msg void OnBnClickedBtnEdit();
public:
 // 删除记录
 CButton m_btnDel;
public:
 afx_msg void OnBnClickedBtnDel();
public:
 afx_msg void OnBnClickedBtnList();
public:
 //窗口显示之前调用
 virtual BOOL OnInitDialog() ;
public:
 //数据库连接串
 string m_cnStr ;
public:
 //列表
 void List() ;
};


///////////////////////////////
// ADOSampleDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "MFC1.h"
#include "ADOSampleDlg.h"
#import "msado15.dll" no_namespace rename("EOF","adoEOF")  //Ado操作组件引入
// CADOSampleDlg 对话框
IMPLEMENT_DYNAMIC(CADOSampleDlg, CDialog)
CADOSampleDlg::CADOSampleDlg(CWnd* pParent /*=NULL*/)
 : CDialog(CADOSampleDlg::IDD, pParent)
{
 char szPath[255] = {0} ;
 ::GetModuleFileName(NULL,szPath,255) ;
 char *p = szPath + strlen(szPath) ;
 while((*p)!='\\'){
  (*p) = '\0' ;
  p-- ;
 }
 strcat(szPath,"Formula.mdb") ;
 char szCnStr[355] = {0} ;
 ::sprintf(szCnStr,"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",szPath) ;
 m_cnStr = szCnStr ;
 //m_cnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= & Server.MapPath(dbpath)" ;
}
CADOSampleDlg::~CADOSampleDlg()
{
}
void CADOSampleDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 DDX_Control(pDX, IDC_BTN_ADD, m_btnAdd);
 DDX_Control(pDX, IDC_BTN_EDIT, m_btnEdit);
 DDX_Control(pDX, IDC_BTN_LIST, m_btnList);
 DDX_Control(pDX, IDC_EDIT_ID, m_ID);
 DDX_Control(pDX, IDC_EDIT_STUDENTNAME, m_EditStudentName);
 DDX_Control(pDX, IDC_EDIT_BIRTHDAY, m_EditBirthday);
 DDX_Control(pDX, IDC_EDIT_GRADE, m_EditGrade);
 DDX_Control(pDX, IDC_EDIT_LIST, m_EditList);
 DDX_Control(pDX, IDC_BTN_DEL, m_btnDel);
}

BEGIN_MESSAGE_MAP(CADOSampleDlg, CDialog)
 ON_BN_CLICKED(IDC_BTN_ADD, &CADOSampleDlg::OnBnClickedBtnAdd)
 ON_BN_CLICKED(IDC_BTN_EDIT, &CADOSampleDlg::OnBnClickedBtnEdit)
 ON_BN_CLICKED(IDC_BTN_DEL, &CADOSampleDlg::OnBnClickedBtnDel)
 ON_BN_CLICKED(IDC_BTN_LIST, &CADOSampleDlg::OnBnClickedBtnList)
END_MESSAGE_MAP()
//窗口显示之前调用
BOOL CADOSampleDlg::OnInitDialog()
{
 CDialog::OnInitDialog() ;
 //m_cnStr = "" ;
 return true ;
}
// CADOSampleDlg 消息处理程序
//添加记录
void CADOSampleDlg::OnBnClickedBtnAdd()
{
 // TODO: 在此添加控件通知处理程序代码
 CString ID("") ;
 CString sName("") ;
 CString sBirthDay("") ;
 CString sGrade("") ;
 m_ID.GetWindowText(ID) ;
 m_EditStudentName.GetWindowText(sName) ;
 m_EditBirthday.GetWindowText(sBirthDay) ;
 m_EditGrade.GetWindowText(sGrade) ;
 
 try{
  _ConnectionPtr pCon ;
  if (FAILED(pCon.CreateInstance("ADODB.Connection")))
  {
   MessageBox("Failed to Connection Create Instance!") ;
   return  ;
  }
  //_variant_t varSRC(m_cnStr);
  _bstr_t bstrSRC(m_cnStr.c_str());
  if (FAILED(pCon->Open(bstrSRC,"","",-1)))
  {
   MessageBox("Fail to Open Connection!") ;
   pCon.Release();
   return  ;
  }
  CString strSql("") ;
  strSql.Format("insert into TZTest(StudentName,BirthDay,Grade) values('%s','%s',%s)",sName,sBirthDay,sGrade) ;
  _variant_t varSQL(strSql);
  
  //COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
  pCon->Execute(_bstr_t(strSql),NULL,adExecuteNoRecords);
  pCon->Close() ;
  pCon.Release() ;
  //CoUninitialize();
  List() ;
 }catch(_com_error e){
  MessageBox(e.ErrorMessage()) ;
  return ;
 }
}
//修改记录
void CADOSampleDlg::OnBnClickedBtnEdit()
{
 // TODO: 在此添加控件通知处理程序代码
 CString ID("") ;
 CString sName("") ;
 CString sBirthDay("") ;
 CString sGrade("") ;
 
 m_ID.GetWindowText(ID) ;
 m_EditStudentName.GetWindowText(sName) ;
 m_EditBirthday.GetWindowText(sBirthDay) ;
 m_EditGrade.GetWindowText(sGrade) ;
 
 try{
  _ConnectionPtr pCn ;
  if(FAILED(pCn.CreateInstance("ADODB.connection"))){
   MessageBox("fail to Create connection Instance") ;
   return ;
  }
  _bstr_t bstrCnStr(m_cnStr.c_str()) ;
  if(FAILED(pCn->Open(bstrCnStr,"","",-1))){
   MessageBox("fail to Open connection!") ;
   return ;
  }
  CString strSql("") ;
  strSql.Format("update TZTest set StudentName='%s',BirthDay='%s',Grade=%s where ID=%s",sName,sBirthDay,sGrade,ID) ;
  pCn->Execute(_bstr_t(strSql),NULL,adExecuteNoRecords) ;
  pCn->Close() ;
  pCn.Release() ;
  List() ;
 }catch(_com_error e){
  MessageBox(e.ErrorMessage()) ;
 }
}
//删除记录
void CADOSampleDlg::OnBnClickedBtnDel()
{
 // TODO: 在此添加控件通知处理程序代码
 CString ID("") ;
 m_ID.GetWindowText(ID) ;
 try{
  _ConnectionPtr pCn ;
  if(FAILED(pCn.CreateInstance("ADODB.connection"))){
   MessageBox("fail to Create Connection Instance!") ;
   return ;
  }
  _bstr_t bstrCnStr(m_cnStr.c_str()) ;
  if(FAILED(pCn->Open(bstrCnStr,"","",-1))){
   MessageBox("fail to Open Connection!") ;
   return ;
  }
  CString strSql("") ;
  strSql.Format("delete from TZTest where ID=%s",ID) ;
  pCn->Execute(_bstr_t(strSql),NULL,adExecuteNoRecords) ;
  pCn->Close() ;
  pCn.Release() ;
  List() ;
 }catch(_com_error e){
  MessageBox(e.ErrorMessage()) ;
  return ;
 }
}
//记录列表
void CADOSampleDlg::OnBnClickedBtnList()
{
 // TODO: 在此添加控件通知处理程序代码
 List() ;
}
//列表
void CADOSampleDlg::List()
{
 //if(CoInitialize(NULL)!=S_OK){
 // MessageBox("CoInitialize err!") ;
 // return ;
 //}
 try{
  _RecordsetPtr pRs;
  if (FAILED(pRs.CreateInstance("ADODB.Recordset")))
  {
   MessageBox("Fail to Create Recordset Instance!") ;
   return ;
  }
  char strSQL[300] = {0} ;
  strcpy(strSQL,"select * from TZTest") ;
  
  //_variant_t varSRC(strSRC);
  _variant_t varSQL(strSQL);
  if(FAILED(pRs->Open(varSQL,m_cnStr.c_str(),adOpenStatic,adLockOptimistic,adCmdText)))
  {
   MessageBox("Fail to Open Sql") ;
   pRs.Release();
   return ;
  }
  CString sContent("") ;
  sContent += "List:\r\n" ;
  while(!pRs->adoEOF){
   char szLine[255] = {0} ;
   string sID = _bstr_t(pRs->GetCollect("ID")) ;
   string sStudentName = _bstr_t(pRs->GetCollect("StudentName")) ;
   string sBirthday = _bstr_t(pRs->GetCollect("Birthday")) ;
   string sGrade = _bstr_t(pRs->GetCollect("Grade")) ;
   sprintf(szLine,"ID:%s,Name:%s,Birth:%s,Grade:%s\r\n",sID.c_str(),sStudentName.c_str(),sBirthday.c_str(),sGrade.c_str()) ;
   sContent += szLine ;
   pRs->MoveNext() ;
  }
  pRs->Close();
  pRs.Release();
  //CoUninitialize() ;
  m_EditList.SetWindowText(sContent) ;
 }catch(_com_error e){
  MessageBox("err!") ;
  MessageBox(e.ErrorMessage()) ;
 }
}
/*
  _ConnectionPtr pCon ;
  if (FAILED(pCon.CreateInstance("ADODB.Connection")))
  {
   CMyClass::WriteFile(m_LogFile,"Create Instance failed!");
   return 2 ;
  }
  _variant_t varSRC(m_cnStr);
  _bstr_t bstrSRC(m_cnStr);
  if (FAILED(pCon->Open(bstrSRC,"","",-1)))
  {
   CMyClass::WriteFile(m_LogFile,"Can not open Database!");
   pCon.Release();
   return -1 ;
  }
  time_t t = 0;
  tm *ltm = NULL ;
  time(&t);  //   get   time
  ltm  = localtime(&t);
  char szEventTime[30] = {0} ;
  sprintf(szEventTime,"%d-%d-%d %d:%d:%d",ltm->tm_year+1900,ltm->tm_mon+1,ltm->tm_mday,ltm->tm_hour,ltm->tm_min,ltm->tm_sec) ;
  int nSqlLen = 150 + strlen(szFromLogin) + strlen(szToLogins) + strlen(szEventTime) + strlen(szEventDetail) ;
  char *strSql = (char*)malloc(sizeof(char)*(nSqlLen+1)) ;
  //free(strSql) ;
  //memset(strSql,0,nSqlLen) ;
  sprintf(strSql,"insert into TITILChatLog(FromLogin,ToLogins,EventType,EventTime,EventDetail) values('%s','%s',%d,'%s','%s')",
   CMyClass::ReplaceStr(szFromLogin,'\'',"''"),CMyClass::ReplaceStr(szToLogins,'\'',"''"),nEventType,szEventTime,CMyClass::ReplaceStr(szEventDetail,'\'',"''")) ;
  //_variant_t varSRC(strSRC);
  _variant_t varSQL(strSql);
  
  //COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
  pCon->Execute(_bstr_t(strSql),NULL,adExecuteNoRecords);
  pCon->Close() ;
  pCon.Release() ;
  //LogFile(gm_LogFile,"操作数据库OK") ;
  free(strSql) ;
  strSql = NULL ;
  //CoUninitialize();
 }catch(_com_error e){
  //MessageBox(NULL,(LPCTSTR)e.Description(),"操作数据库错误",MB_OK|MB_ICONERROR);
  //LogFile(gm_LogFile,"操作数据库错误") ;
  //CoUninitialize();
  CMyClass::WriteFileWithSysTime(m_LogFile,"Error:CServiceFuns::EventLog-1 系统出现异常\r\n") ;
  return 4 ;
 }
///////////////////////////////////////////////////////////////////////
 try{
  _RecordsetPtr pPtr;
  if (FAILED(pPtr.CreateInstance("ADODB.Recordset")))
  {
   CMyClass::WriteFile(m_LogFile,"Create Instance failed!");
   EventLog(LoginName,"",ITILCHAT_LOGIN,"登录失败,Create Instance failed!") ;
   return 2 ;
  }
  CMD5 md5 ;
  md5.setPlainText(Pwd) ;
  char *szLoginName = CMyClass::ReplaceStr(LoginName,'\'',"''");
  const char *szPwd = md5.getMD5Digest() ;
  
  char strSQL[300] = {0} ;
  sprintf(strSQL,"select LoginName,Compellation from TEntry where LoginName='%s' and LogPwd='%s'",szLoginName,szPwd) ;
  
  //_variant_t varSRC(strSRC);
  _variant_t varSQL(strSQL);
  if(FAILED(pPtr->Open(varSQL,m_cnStr,adOpenStatic,adLockOptimistic,adCmdText)))
  {
   printf("Open table failed!");
   EventLog(LoginName,"",ITILCHAT_LOGIN,"登录失败,Open table failed!") ;
   pPtr.Release();
   return 3;
  }
  if(!pPtr->adoEOF){
   string sEmployeeID = _bstr_t(pPtr->GetCollect("LoginName")) ;
   string sNickName = _bstr_t(pPtr->GetCollect("Compellation")) ;
   //int nEmployeeID = atoi(sEmployeeID.c_str()) ;
   //loginInfo.client = NULL ;
   loginInfo.EmployeeID = 0 ;
   //loginInfo.IP = NULL ;
   //loginInfo.Port = 0 ;
   strcpy(loginInfo.LoginName,LoginName) ;
   strcpy(loginInfo.NickName,sNickName.c_str()) ;
   loginInfo.State = 1 ;
   loginInfo.StateMsg[0] = '\0' ;
   nRet = 0 ;
  }
  pPtr->Close();
  pPtr.Release();
  if(nRet==0){
   EventLog(LoginName,"",ITILCHAT_LOGIN,"登录成功") ;
  }else{
   EventLog(LoginName,"",ITILCHAT_LOGIN,"登录失败") ;
  }
  //LogFile(gm_LogFile,"操作数据库OK") ;
  CMyClass::FreeMem(&szLoginName) ;
  //CoUninitialize();
 }catch(_com_error e){
  //MessageBox(NULL,(LPCTSTR)e.Description(),"操作数据库错误",MB_OK|MB_ICONERROR);
  //LogFile(gm_LogFile,"操作数据库错误") ;
  EventLog(LoginName,"",ITILCHAT_LOGIN,"登录失败,系统发生异常") ;
  //CoUninitialize();
  CMyClass::WriteFileWithSysTime(m_LogFile,"Error:CServiceFuns::Login--0-1 系统出现异常\r\n") ;
  return 4 ;
 }
*/
阅读(1642) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~