ADO学习(八)源码示例

来源:互联网 发布:淘宝抢购插件 编辑:程序博客网 时间:2024/06/05 01:02

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <icrsint.h>
//其中icrsint.h文件包含了VC++扩展的一些预处理指令、宏等的定义,用于COM编程时使用。

//放在所有include的后面
//#import "C:/Program Files/Common Files/System/ADO/msado15.dll" named_guids rename("EOF","adoEOF"), rename("BOF","adoBOF")
#import "C:/Program Files/Common Files/System/ADO/msado15.dll" named_guids rename("EOF","adoEOF"), rename("BOF","adoBOF")


//不知道named_guids是干嘛的?????????

using namespace ADODB;
/*
msado15.dll使用的命名空间是ADODB,故此使用using namespace ADODB;

方法二:
#import "C:/Program Files/Common Files/System/ADO/msado15.dll" no_namespace rename("EOF","adoEOF"), rename("BOF","adoBOF")
//不用使用命名空间

方法三:
#import "C:/Program Files/Common Files/System/ADO/msado15.dll" rename_namespace("NEWSPACE") rename("EOF","adoEOF"), rename("BOF","adoBOF")
using namespace NEWSPACE;

*/

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 // TODO: 在此添加额外的初始化代码

 //使用COM的初始化
 HRESULT hr = CoInitialize(NULL);
 ASSERT(SUCCEEDED(hr));
 //或者(AfxOleInit只能在MFC中使用)
 //AfxOleInit();

 /*
 初始化OLE/COM库
 AfxOleInit();
 或者
 ::CoInitialize(NULL);
 (据说AfxOleInit只能在MFC中使用)
 实现方法:
 if(!AfxOleInit())
 {               
 AfxMessageBox(("COM Error!"));   
 }
 AfxOleInit()是初始化Ole的运行环境,Ole是在Com的基础上作的扩展,是ActiveX运行的基础。AfxOleInit()调用的是OleInitialize(),而OleInitialize()除了调用CoInitializeEx()来初始化COM库外,还进行一些其它的操作,这些操作对OLE应用来说是必须的,这些OLE应用包括:  
 (1)Clipboard;  
 (2)Drag and drop;  
 (3)Object linking and embedding(现在的OLE,已不再仅仅是Object        linking        and        embedding的概念);  
 4)In-place        activation;  
 与AfxOleInit()对应的是,AfxOleTerm()。  
 CoInitialize CoInitializeEx 是用来初始化COM运行环境的。CoInitialize和CoUninitialize必须成对使用。
 AfxOleInit()和AfxOleTerm()其实也是需要成对的,但是,在你的程序中,AfxOleTerm()可以不出现,这是因为,MFC已经帮你做好了。
 */
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

//按钮响应
void CADO_STUDYDlg::OnBnClickedButton1()
{
 // TODO: 在此添加控件通知处理程序代码

 try
 {
  //创建实例
  m_pConnection.CreateInstance("ADODB.Connection");
  //或者  __uuidof使取类型的GUID
  //m_pConnection.CreateInstance(__uuidof(Connection));

  //方法一:字符串数据源
  //或者也可以不对ConnectionString进行赋值,直接写在open的第一个参数里面
  m_pConnection->ConnectionString = "Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=CAMPUS;Data Source=192.168.0.102";
  
  //连接超时为5秒
  m_pConnection->ConnectionTimeout = 5;
  
  m_pConnection->Open("","","",adModeUnknown);
  /*
  参数一:连接字符串
  参数二:用户名
  参数三:用户密码
  参数四:
  adModeUnknown:缺省。当前的许可权未设置
  adModeRead:只读
  adModeWrite:只写
  adModeReadWrite:可以读写
  adModeShareDenyRead:阻止其它Connection对象以读权限打开连接
  adModeShareDenyWrite:阻止其它Connection对象以写权限打开连接
  adModeShareExclusive:阻止其它Connection对象打开连接
  adModeShareDenyNone:允许其它程序或对象以任何权限建立连接
  */


//   //方法二字符串数据源
//   char m_szConnStr[MAX_PATH];
//   char szUdlPath[MAX_PATH] ={".\\campus.udl"};//可相对路径,亦可绝对路径
//   sprintf(m_szConnStr,"File Name=%s", szUdlPath);//前面是固定格式
//   m_pConnection->Open((_bstr_t)(m_szConnStr),"","",adModeUnknown);

  //状态校验
  ASSERT(m_pConnection->State == adStateOpen);

  //执行SQL语句
  CString szsql = _T("select * from student");
  /*
  CString szsql = _T("insert into student values('1007','xiaoming','101')");
  CString szsql = _T("delete from student where SID='1007'");
  CString szsql = _T("uddate student set SNAME = 'xiaoming'where SID='1001'");
  利用m_pConnection->Execute()完成增删改完全没有问题,查询的时候要有一个变量来储存返回来的结果集
  */

  _RecordsetPtr pRst;
  _variant_t RecordsAffected;
  pRst = m_pConnection->Execute((_bstr_t)szsql, &RecordsAffected, adCmdText);
  /*
  参数三:
  adCmdText:表明CommandText是文本命令
  adCmdTable:表明CommandText是一个表名
  adCmdProc:表明CommandText是一个存储过程
  adCmdUnknown:未知
  */

  //这里应该有一个数据集校验的逻辑  if(pRst->State == 1) ;

//   //以下两种方式都可以
//   //while (pRst->adoEOF!=VARIANT_FALSE)
//   while (!pRst->adoEOF)
//   {
//    CString SID=(_bstr_t)(pRst->Fields->GetItem(_variant_t("SID"))->Value);
//    //或者使用CString SID=(_bstr_t)(pRst->Fields->GetItem(_variant_t("SID"))->GetValue());
//    CString SNAME=(_bstr_t)(pRst->Fields->GetItem(_variant_t("SNAME"))->Value);
//     CString TID=(_bstr_t)(pRst->Fields->GetItem(_variant_t("TID"))->Value);
//    gConsoleLog.WriteLogInfo("%s--->%s--->%s", SID,SNAME,TID);
//
//    //利用pRst指针修改数据
// //    if (SID.Find("1001")>=0)
// //    {
// //     //当然光标要支持更新
// //     //方法一:
// //     pRst->Fields->GetItem(_variant_t("SNAME"))->Value = "111111111";
// //     //方法二:
// //     pRst->Fields->GetItem(_variant_t("SNAME"))->PutValue(_bstr_t("赵薇"));
// //    }
//    pRst->MoveNext();
//   }

  //////////////////////////////////////////////////////////////////////////////////////
  //利用pRst指针添加数据
//   try
//   {
//    /*
//    新记录添加成功后,即自动成为当前记录。AddNew方法有两种形式,一个含有参数,而另一个则不带参数。
//    */
//    //方法一(不带参数):
//    if (!pRst->Supports(adAddNew)) return;
//    pRst->AddNew();
//    pRst->Fields->GetItem(_variant_t("SID"))->Value = "1008";
//    pRst->Fields->GetItem(_variant_t("SNAME"))->Value = "addnew";
//    pRst->Fields->GetItem(_variant_t("TID"))->Value = "102";
//    pRst->Update();
//   }
//   catch (_com_error &e)
//   {
//    AfxMessageBox(e.Description());
//    AfxMessageBox(e.ErrorMessage());
//   }
  //////////////////////////////////////////////////////////////////////////////////////
  //利用pRst指针删除数据
//   try
//   {
//    pRst->MoveFirst();
//    //pRst->Delete(1);
//    pRst->Update();
//    pRst->MoveFirst();
//   }
//   catch (_com_error &e)
//   {
//    AfxMessageBox(e.Description());
//    AfxMessageBox(e.ErrorMessage());
//   }

  //////////////////////////////////////////////////////////////////////////
  //command对象执行sql语句
  //Command对象在进行存储过程的调用中能真正体现它的作用
  _CommandPtr m_pCommand;
  m_pCommand.CreateInstance(__uuidof(Command));
  _variant_t vNULL;
  vNULL.vt = VT_ERROR;
  vNULL.scode = DISP_E_PARAMNOTFOUND;

  m_pCommand->ActiveConnection = m_pConnection;
  m_pCommand->CommandText = "select * from student";
  pRst = m_pCommand->Execute(&vNULL,&vNULL,adCmdText);

  while (!pRst->adoEOF)
  {
   CString SID=(_bstr_t)(pRst->Fields->GetItem(_variant_t("SID"))->Value);
   //或者使用CString SID=(_bstr_t)(pRst->Fields->GetItem(_variant_t("SID"))->GetValue());
   CString SNAME=(_bstr_t)(pRst->Fields->GetItem(_variant_t("SNAME"))->Value);
   CString TID=(_bstr_t)(pRst->Fields->GetItem(_variant_t("TID"))->Value);
   gConsoleLog.WriteLogInfo("%s--->%s--->%s", SID,SNAME,TID);

   pRst->MoveNext();
  }

  //////////////////////////////////////////////////////////////////////////

  //释放并关闭连接
  if (m_pConnection->State == adStateOpen)
  {
   //先后顺序错乱会导致程序崩溃
   m_pConnection->Release();
   m_pConnection->Close();

  }

  //卸载com库
  ::CoUninitialize();

 }
 catch (_com_error &e)
 {
  AfxMessageBox(e.Description());
  AfxMessageBox(e.ErrorMessage());
 }
}

void CADO_STUDYDlg::OnBnClickedButton2()
{
 // TODO: 在此添加控件通知处理程序代码

 //ADO使无法建立数据库的
//  _bstr_t strcnn1(_T("Provider=Microsoft.JET.OLEDB.4.0;Data source=student.mdb"));
//  try
//  {
//   m_pConnection.CreateInstance(__uuidof(Connection));
//   m_pConnection->Open(strcnn1,  _T(""), _T(""), adModeUnknown);
//   m_pRecordset.CreateInstance(__uuidof(Recordset));
//  }
//  catch(_com_error e)
//  {
//   AfxMessageBox(_T("建立数据库失败!"), MB_OK|MB_ICONSTOP);
//  }
//  return ;

 TCHAR szPathName[MAX_PATH];
 GetModuleFileName(NULL, szPathName, MAX_PATH);
 CString strPath = szPathName;
 int nPos;  
 nPos = strPath.ReverseFind (_T('\\'));  
 strPath = strPath.Left(nPos);
 strPath  += _T("\\student.mdb");
 CFileFind ff;
 if(ff.FindFile(strPath)) //如果没有找到该数据库文件则重建此文件夹
 { 
  AfxMessageBox(_T("已经存在数据库文件"));
  return; 
 }
 CString strConnection;
 strConnection.Format(_T("Provider=Microsoft.JET.OLEDB.4.0;Data source=%s"), strPath);
 _bstr_t strcnn(strConnection);
 HRESULT hr = m_pCatalog.CreateInstance(__uuidof(ADOX::Catalog));
 if(FAILED(hr))
 {
  AfxMessageBox(_T("创建ADOX实例失败"));
  return;
 }
 try
 {
  m_pCatalog->Create(strcnn);
  m_pConnection.CreateInstance(__uuidof(Connection));
  m_pConnection->Open(strcnn,  _T(""), _T(""), adModeUnknown);
  CString strSql = _T("create table StudentInfo(student_id varchar(20) not null, \
       student_name varchar(20) not null, score int)");
  m_pConnection->Execute((_bstr_t)strSql, NULL, adCmdText);
 }
 catch(_com_error e)
 {
  AfxMessageBox(_T("创建MDB文件失败"));
 }

}

void CADO_STUDYDlg::OnBnClickedButton3()
{
 // TODO: 在此添加控件通知处理程序代码

 try
 {
  m_pConnection.CreateInstance("ADODB.Connection");
  m_pConnection->ConnectionString = "Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=CAMPUS;Data Source=192.168.0.102";
  m_pConnection->ConnectionTimeout = 5;
  //客户端游标(不适用此游标就不能使用DataGrid控件)
  m_pConnection->CursorLocation = adUseClient;
  m_pConnection->Open("","","",adModeUnknown);

  _RecordsetPtr m_pRecordset;
  m_pRecordset.CreateInstance(__uuidof(Recordset));

  CString strsql;
  strsql.Format(_T("select * from CAMPUS..STUDENT order by sname asc"));

  //以下两种方式都是可以的
  //m_pRecordset->Open(_bstr_t(strsql), (IDispatch*)m_pConnection, adOpenDynamic,adLockOptimistic,adCmdText);
  m_pRecordset->Open(_bstr_t(strsql), m_pConnection.GetInterfacePtr(), adOpenDynamic,adLockOptimistic,adCmdText);

  CString SID,SNAME,TID;
  _variant_t vt;
  while (!m_pRecordset->adoEOF)
  {
   //SID=(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("SID"))->Value);
   vt = m_pRecordset->GetCollect("SID");
   if (vt.vt != VT_NULL) SID=(LPCSTR)_bstr_t(vt);

   SNAME=(LPCSTR)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("SNAME"))->Value);
   TID=(LPCSTR)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("TID"))->Value);

   gConsoleLog.WriteLogInfo("%s--->%s--->%s", SID,SNAME,TID);

   m_pRecordset->MoveNext();
  }

  m_DataGrid.put_AllowAddNew(TRUE);
  m_DataGrid.put_AllowDelete(TRUE);
  m_DataGrid.put_Caption(_T("学生成绩表"));
  m_DataGrid.putref_DataSource(m_pRecordset);

 }
 catch (_com_error &e)
 {
  AfxMessageBox(e.Description());
  AfxMessageBox(e.ErrorMessage());
 }


}

void CADO_STUDYDlg::OnBnClickedButton4()
{
 // TODO: 在此添加控件通知处理程序代码

 m_pConnection.CreateInstance(__uuidof(Connection));//创建连接对象实例
 try                
 { 
  // 打开本地Access库AddressBook.mdb
  m_pConnection->Open("Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=CAMPUS;Data Source=192.168.0.102","","",adModeUnknown);
 }
 catch(_com_error e)
 {
  AfxMessageBox("数据库连接失败,确认数据库AddressBook.mdb是否在当前路径下!");
  return;
 }

 m_pRecordset.CreateInstance(__uuidof(Recordset));//创建记录集对象
 try
 {
  m_pRecordset->Open("SELECT * FROM STUDENT",         // 查询STUDENT表中所有字段
   m_pConnection.GetInterfacePtr(),    // 获取库接库的IDispatch指针
   adOpenDynamic,
   adLockOptimistic,
   adCmdText);
 }
 /*
 参数三:
 adOpenDynamic     允许添加、修改和删除记录,支持所有方式的光标移动,其他用户的修改可以在联机以后仍然可见
 adOpenKeyset      类似于adOpenDynamic光标,它支持所有类型的光标移动,但是建立连接以后其他用户对记录的添加不可见,其他用户对记录的删除和对数据的修改是可见的。支持书签操作
 adOpenStatic      支持各种方式的光标移动,但是建立连接以后其他用户的行添加、行删除和数据修改都不可见,支持书签操作
 adOpenForwardOnly 只允许向前存取,而且在建立连接以后,其他用户的行添加、行删除和数据修改都不可见,支持书签操作

 参数四:
 adLockReadOnly(缺省)数据只读
 adLockPessimistic锁定操作的所有行,也称为消极锁定
 adLockOptimistic只在调用Update方法时锁定操作的行,也称为积极锁定
 adLockBatchOptimistic在批量更新时使用该锁定,也称为积极批量锁定

 

 */
 catch(_com_error *e)
 {
  AfxMessageBox(e->ErrorMessage());
 } 

 //添加新记录
 m_pRecordset->AddNew();
 m_pRecordset->PutCollect("SID",_variant_t("1007"));
 m_pRecordset->PutCollect("SNAME",_variant_t("liuxiong"));
 m_pRecordset->PutCollect("TID", _variant_t("102"));
 m_pRecordset->Update();

 m_pRecordset->Close();//关闭记录集对象
 m_pRecordset = NULL;

 if(m_pConnection->State)
  m_pConnection->Close();//关闭连接对象
 m_pConnection= NULL; 
}

void CADO_STUDYDlg::OnBnClickedButton5()
{
 // TODO: 在此添加控件通知处理程序代码

 //_CommandPtr对象的优势就在于执行存储过程中可以传递参数
 m_pConnection.CreateInstance(__uuidof(Connection));//创建连接对象实例
 try                
 { 
  m_pConnection->Open("Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=CAMPUS;Data Source=192.168.0.102","","",adModeUnknown);
 
  //存储过程名
  _bstr_t storproc("procname");
  _bstr_t name("1002");
  _CommandPtr pCommand;
  pCommand.CreateInstance(__uuidof(Command));
  pCommand->ActiveConnection=m_pConnection;
  //指定CommandTexe属性为存储过程名
  pCommand->CommandText=storproc;
  //指定CommandType属性为存储过程类型
  pCommand->CommandType=adCmdStoredProc;
  //在给参数赋值前调用Refresh方法
  pCommand->Parameters->Refresh();
  //给存储过程的参数赋值
  pCommand->Parameters->Item[_variant_t((long)1)]->Value=_variant_t((LPCTSTR)name);
  //执行存储过程,返回_RecordsetPtr类型指针,因为在CommandText中指定了命令,在Execute方法中参数赋空值就可了
  m_pRecordset=pCommand->Execute(NULL,NULL,adCmdStoredProc);


  CString SID,SNAME,TID;
  _variant_t vt;
  while (!m_pRecordset->adoEOF)
  {
   //SID=(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("SID"))->Value);
   vt = m_pRecordset->GetCollect("SID");
   if (vt.vt != VT_NULL) SID=(LPCSTR)_bstr_t(vt);

   SNAME=(LPCSTR)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("SNAME"))->Value);
   TID=(LPCSTR)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("TID"))->Value);

   gConsoleLog.WriteLogInfo("%s--->%s--->%s", SID,SNAME,TID);

   m_pRecordset->MoveNext();
  }
 
 }
 catch(_com_error e)
 {
  AfxMessageBox(e.Description());
  return;
 }

}

0 0
原创粉丝点击