VC下的ADO编程入门(2-4)

类别:VC语言 点击:0 评论:0 推荐:

好了,现在我们正式进入本主题,Let's go

 

n          新建一个基于对话的应用程序zjy,在对话框上添加一个按钮和列表控件,并把列表控件的样式设置为报表视图,还有用classwizard给列表控件添加一个控件变量m_list

n          在StdAfx.h头文件中添加一条如下语句

#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")

n          在zjy.cpp开始处添加自动初始化COM库的代码

struct InitOle

{

         InitOle(){::CoInitialize(NULL);}

         ~InitOle(){::CoUninitialize();}

}_init_InitOle_;

n          在zjyDlg.h中添加三个成员变量

         bool m_IsConnectionOpen;

         _ConnectionPtr m_pConnection;

         _RecordsetPtr m_pRecordset;

n          在zjyDlg.cpp的BOOL CZjyDlg::OnInitDialog()的      return TRUE;前面添加如下代码

// TODO: Add extra initialization here

         HRESULT hr;

         _bstr_t bstrQuery("select * from customers");

         _bstr_t strConnect="Provider=SQLOLEDB; data source=127.0.0.1;initial catalog=Northwind;";

         _variant_t vRecsAffected(0L);

        

         _variant_t vNULL;

         vNULL.vt=VT_ERROR;

         vNULL.scode =DISP_E_PARAMNOTFOUND;

 

         try

         {

                   hr=m_pConnection.CreateInstance(__uuidof(Connection));

                   if(SUCCEEDED(hr))

                   {

                            hr=m_pConnection->Open(strConnect,_bstr_t(L"sa"),_bstr_t(L""),adConnectUnspecified);

                            if(SUCCEEDED(hr))

                            {

                                     hr=m_pRecordset.CreateInstance(__uuidof(Recordset));

                                     if(SUCCEEDED(hr))

                                     {

                                               m_pRecordset->PutRefActiveConnection(m_pConnection);

                                               hr=m_pRecordset->Open(_variant_t(bstrQuery),vNULL,adOpenDynamic,adLockOptimistic,adCmdText);

                                               if(SUCCEEDED(hr))

                                               {

                                                         m_IsConnectionOpen=true;

                                               }

                                     }

                            }

                   }

         }

         catch(_com_error &e)

         {

                   _bstr_t bstrSource(e.Source());

                   _bstr_t bstrDescription(e.Description());

                   TRACE("Exception throw for classes generated by #import");

                   TRACE("\tCode=%08lx\n", e.Error);

                   TRACE("\tCode meaning = %s\n", e.ErrorMessage);

                   TRACE("\tSource = %s\n", (LPCTSTR)bstrSource);

                   TRACE("\tDescription = %s\n", (LPCTSTR)bstrDescription);

         }

         catch(...)

         {

                   TRACE("Unhandled Exception");

         }

n          添加对话框的WM_Destroy消息响应函数

void CZjyDlg::OnDestroy()

{

         CDialog::OnDestroy();

        

         // TODO: Add your message handler code here

         if(m_IsConnectionOpen)

         {

                    m_IsConnectionOpen=false;

                    m_pConnection->Close();

                    

                    m_pConnection=NULL;

                    m_pRecordset=NULL;

         }

}

n          最后添加按钮的消息响应函数如下

void CZjyDlg::OnButton1()

{

         // TODO: Add your control notification handler code here

         VARIANT_BOOL valEof;

        

         HRESULT hr;

        

         CString strColName;BSTR bstrColName;

 

         CString strValue;VARIANT varValue;

 

         long  ColCount,i; int RowCount=0;

         Fields * fields=NULL;Field * field=NULL;

 

         VARIANT varCounter;

         varCounter.vt=VT_I4;

         varCounter.lVal=0;

 

         try

         {

                   m_list.DeleteAllItems();

                   while(m_list.DeleteColumn(0));

 

                   hr=m_pRecordset->get_Fields(&fields);

                   if(SUCCEEDED(hr)) hr=fields->get_Count(&ColCount);

                   for(i=0;i<ColCount;i++)

                   {       

                            hr=fields->Item[i]->get_Name(&bstrColName);

                            strColName=bstrColName;

                            int nWidth=m_list.GetStringWidth(strColName)+15;

                            m_list.InsertColumn(i,strColName,LVCFMT_LEFT,nWidth);

                   }

                   if(SUCCEEDED(hr)) fields->Release();

 

                   m_pRecordset->get_adoEOF(&valEof);

                   while(true)

                   {

                            if(valEof)break;

                            m_pRecordset->Fields->get_Item(varCounter,&field);

                            field->get_Value(&varValue);

                            strValue=VariantToString(varValue);

                            m_list.InsertItem(RowCount,strValue);

                            for(i=1;i<ColCount;i++)

                            {

                                     varCounter.lVal =i;

                                     m_pRecordset->Fields->get_Item(varCounter,&field);

                                     field->get_Value(&varValue);

                                     strValue=VariantToString(varValue);

                                     m_list.SetItemText(RowCount,i,(LPCTSTR)strValue);

                            }

                            RowCount++;

                            m_pRecordset->MoveNext();

                            m_pRecordset->get_adoEOF(&valEof);

                            varCounter.lVal=0;

                   }

                   m_pRecordset->Close();

         }

         catch(_com_error &e)

         {

                   _bstr_t bstrSource(e.Source());

                   _bstr_t bstrDescription(e.Description());

                   TRACE("\tCode=%08lx\n", e.Error);

                   TRACE("\tCode meaning = %s\n", e.ErrorMessage);

                   TRACE("\tSource = %s\n", (LPCTSTR)bstrSource);

                   TRACE("\tDescription = %s\n", (LPCTSTR)bstrDescription);

         }

         catch(...)

         {

 

         }

}

n          还有还有,在对话框类添加一个数据类型转换函数

CString CZjyDlg::VariantToString(VARIANT var)

{

CString strValue;

         _variant_t var_t;

         _bstr_t bstr_t;

         time_t cur_time;

         CTime time_value;

         COleCurrency var_currency;

         switch(var.vt)

         {

         case VT_EMPTY:

         case VT_NULL:strValue=_T("");break;

         case VT_UI1:strValue.Format("%d",var.bVal);break;

         case VT_I2:strValue.Format("%d",var.iVal);break;

         case VT_I4:strValue.Format("%d",var.lVal);break;

         case VT_R4:strValue.Format("%f",var.fltVal);break;

         case VT_R8:strValue.Format("%f",var.dblVal);break;

         case VT_CY:

                   var_currency=var;

                   strValue=var_currency.Format(0);break;

         case VT_BSTR:

                   var_t =var;

                   bstr_t=var_t;

                   strValue.Format("%s",(const char *)bstr_t);break;

         case VT_DATE:

                   cur_time=var.date;

                   time_value=cur_time;

                   strValue.Format("%A,%B,%d,%Y");break;

         case VT_BOOL:strValue.Format("%d",var.boolVal);break;

         default:strValue=_T("");break;

         }

         return strValue;

}

(完)

下一篇介绍如何对记录进行增删改操作。

本文地址:http://com.8s8s.com/it/it1127.htm