zoukankan      html  css  js  c++  java
  • [转]VC下ADO数据库操作的封装类

    转自:http://www.cppblog.com/changshoumeng/archive/2010/05/12/115216.html

    代码如下:

      1 /******************************************************************
      2  模块名称:数据库操作类;
      3  实现功能:提供接口,实现数据的索引,和操作。
      4  研究人员:长寿梦;
      5  最后更新:2010-05-12
      6 
      7  预先操作:
      8  【1】在stdafx.h中添加
      9     #import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
     10  【2】在主进程的InitInstance()中添加
     11          if(!AfxOleInit())
     12         {
     13          AfxMessageBox("OLE初始化错误");
     14          return FALSE;
     15          }
     16 
     17  【3】在.cpp文件中要包含"CPFile.h"
     18 *********************************************************************/
     19 
     20 /*****************************************************************
     21 CPFile.h
     22 ******************************************************************/
     23 class CPData  
     24 {
     25 public:
     26     
     27     //默认初始化构造函数
     28     CPData();
     29     
     30     //传入连接的构造函数
     31     CPData(_ConnectionPtr pConnection);
     32     
     33     //析构函数
     34     virtual ~CPData();
     35 public:
     36     
     37     //连接数据库
     38     BOOL Connect(CString strUser,CString strPassword,CString strFileName="ConnectionParam.udl",int nOptions=-1,CString strConStr="Provider=sqloledb.1;Data Source=(local);Database=VLan");
     39     
     40     //关闭数据库的连接
     41     void DisConnect();
     42     
     43     //数据库查询语句,用来对数据库的各种字段进行查询
     44     //如果成功返回TRUE,否则返回FALSE.查询的结果存储在类的共有成员变量m_pRecordset中
     45     //查询结果的行数和列数分别保存在共有成员变量m_nResultRow和m_nResultCol中
     46     BOOL Select(CString strSql);
     47     
     48     //查询语句,负责对仅仅查询一个字段的情况进行处理
     49     //结果存放在CStringArray类型的变量pResult中
     50     BOOL Select(CString strSql,CStringArray& Result);
     51     
     52     //对多个字段进行查询
     53     BOOL SelectMulitCol(CString strSql,CStringArray& Result);
     54     
     55     //打开表
     56     BOOL OpenTable(CString strTable);
     57     
     58     //打开表
     59     BOOL OpenTable(CString strTable,CStringArray& Result);
     60     
     61     //进行其它的更新操作
     62     BOOL Execute(CString strSql);
     63 public:
     64     BOOL ExecuteTrans(CStringArray& aSql);    
     65     
     66     //关闭结果集合
     67     void CloseRecordset();
     68     
     69     //得到操作结果的列数
     70     long GetResultCol();
     71     
     72     //得到操作结果的条数
     73     long GetResultRow();
     74     
     75     //得到操作结果
     76     _RecordsetPtr GetResult();
     77 private:
     78     
     79     //数据库操作返回的结果条数
     80     long m_nResultRow;
     81     
     82     //返回的_RecordsetPtr中列数
     83     long m_nResultCol;
     84     
     85     //连接指针
     86     _ConnectionPtr m_pConnection;
     87     
     88     //命令执行指针
     89     _CommandPtr m_pCommand;
     90     
     91     //结果集指针
     92     _RecordsetPtr m_pRecordset;
     93 };
     94 
     95 /**************************************************************
     96 CPFile.cpp
     97 **************************************************************/
     98 
     99 //////////////////////////////////////////////////////////////////////
    100 // 构造函数
    101 //////////////////////////////////////////////////////////////////////
    102 //默认的构造函数
    103 CPData::CPData()
    104 {
    105     //初始化
    106     m_nResultRow = 0;
    107     m_nResultCol=0;
    108     m_pConnection = NULL;
    109     //创建对象
    110     m_pRecordset.CreateInstance(_uuidof(Recordset));
    111     m_pCommand.CreateInstance(_uuidof(Command)); 
    112 }
    113 
    114 //传入参数的构造函数
    115 CPData::CPData(_ConnectionPtr pConnection)
    116 {
    117     m_pConnection = pConnection; 
    118     m_nResultRow = 0;
    119     m_nResultCol=0;
    120     //创建对象
    121     m_pRecordset.CreateInstance(_uuidof(Recordset));
    122     m_pCommand.CreateInstance(_uuidof(Command)); 
    123     
    124 }
    125 //////////////////////////////////////////////////////////////////////
    126 // 析构函数
    127 //////////////////////////////////////////////////////////////////////
    128 CPData::~CPData()
    129 { 
    130     if(m_pRecordset->State!=adStateClosed)
    131         m_pRecordset->Close();
    132     m_pRecordset = NULL;
    133 
    134     if(m_pCommand->State!=adStateClosed)
    135         m_pCommand->Release();
    136     m_pCommand = NULL;
    137 
    138     if(m_pConnection->State!=adStateClosed) 
    139         m_pConnection->Close();
    140     m_pConnection = NULL; 
    141 }
    142 
    143 /////////////////////////////////////////////////////////////////////
    144 ///简单操作函数
    145 ////////////////////////////////////////////////////////////////////
    146 
    147 //得到操作结果的行数
    148 long CPData::GetResultRow()
    149 {
    150     return this->m_nResultRow;
    151 }
    152 
    153 //得到操作结果的列数
    154 long CPData::GetResultCol()
    155 {
    156     return this->m_nResultCol;
    157 }
    158 
    159 //得到操作结果
    160 _RecordsetPtr CPData::GetResult()
    161 {
    162     return this->m_pRecordset;
    163 }
    164 
    165 ///////////////////////////////////////////////////////////////////////
    166 ///连接操作
    167 ///////////////////////////////////////////////////////////////////////
    168 
    169 //连接到数据库
    170 //1.连接字符串可以自己构造,也可以从文件中读出
    171 BOOL CPData::Connect(CString strUser,CString strPassword,CString strFileName,int nOptions,CString strConStr)
    172 {
    173     try{ 
    174         m_pConnection.CreateInstance(__uuidof(Connection));
    175         HRESULT hr;
    176         //如果用文件方式配置数据源,进行配置
    177         if(strFileName.Compare("")!=0&&CPFile::IsFileExist(strFileName))
    178         {
    179             CString con = "File Name="+strFileName;
    180             m_pConnection->ConnectionString =(_bstr_t)con;
    181             hr=m_pConnection->Open("","","",nOptions);    
    182         }
    183         else
    184         {
    185             //自己配置连接字符串
    186             m_pConnection->ConnectionString = (_bstr_t)strConStr;
    187             hr=m_pConnection->Open("",_bstr_t(strUser),_bstr_t(strPassword),nOptions);  
    188         }
    189         //进行连接
    190         //连接失败
    191         if(FAILED(hr))
    192         {   
    193             AfxMessageBox("连接失败!");
    194             return FALSE;
    195         }
    196     }
    197     catch(_com_error&e)
    198     {
    199         AfxMessageBox(e.Description()+"B");
    200         return FALSE;
    201     } 
    202     return TRUE;
    203 }
    204 
    205 //断开连接
    206 void CPData::DisConnect()
    207 {
    208     if(m_pConnection->State!=adStateClosed)
    209         m_pConnection->Close(); 
    210 }
    211 
    212 ///////////////////////////////////////////////////////////////////////
    213 ///更新操作
    214 ///////////////////////////////////////////////////////////////////////
    215 BOOL CPData::Execute(CString strSql)
    216 {
    217     try
    218     {
    219         _variant_t vNULL;
    220         vNULL.vt = VT_ERROR;
    221         
    222         ///定义为无参数
    223         vNULL.scode = DISP_E_PARAMNOTFOUND;
    224         
    225         ///非常关键的一句,将建立的连接赋值给它
    226         m_pCommand->ActiveConnection = m_pConnection;
    227         
    228         ///命令字串
    229         m_pCommand->CommandText = (_bstr_t)strSql;
    230         
    231         ///执行命令,取得记录集
    232         m_pRecordset = m_pCommand->Execute(&vNULL,&vNULL,adCmdText);
    233         
    234         //确实,vNULL中的intVal是执行操作所影响的行数
    235         m_nResultRow = 0;
    236         m_nResultRow = vNULL.intVal;  
    237     }
    238     catch(_com_error&e)
    239     {
    240         m_nResultRow = 0;  
    241         return FALSE;
    242     }
    243     return TRUE;
    244 }
    245 
    246 ///////////////////////////////////////////////////////////////////////
    247 ///查询操作
    248 ///////////////////////////////////////////////////////////////////////
    249 BOOL CPData::Select(CString strSql)
    250 {
    251     try
    252     {
    253         m_nResultCol=0;
    254         m_nResultRow=0;  
    255         m_pRecordset->CursorLocation=adUseClient;    //设置游标位置,设置为客户端形式,否则GetRecordCount()返回值不对
    256         m_pRecordset->Open(_variant_t(strSql),_variant_t((IDispatch *)m_pConnection,true),adOpenDynamic,adLockOptimistic,adCmdText);
    257         m_nResultCol = m_pRecordset->Fields->GetCount();//得到查询结果的列数
    258         m_nResultRow = m_pRecordset->GetRecordCount();  //得到查询结果的行数
    259     }
    260     catch(_com_error&e)
    261     {  
    262         AfxMessageBox(e.Description()+"D");
    263         return FALSE;
    264     }
    265     return TRUE;
    266 }
    267 
    268 //查询语句,负责对仅仅查询一个字段的情况进行处理
    269 //结果存放在CStringArray类型的变量pResult中
    270 BOOL CPData::Select(CString strSql,CStringArray& Result)
    271 {
    272     if(Select(strSql)!=0)
    273     {
    274         Result.RemoveAll();
    275         for(int i=0;i<m_nResultRow;i++)
    276         {
    277             _variant_t value;
    278             value=m_pRecordset->Fields->Item[(long)0]->Value;   
    279             if(value.vt==3||value.vt==14)
    280             {
    281                 CString strTrans;
    282                 strTrans.Format("%ld",value.intVal);
    283                 Result.Add(strTrans);
    284             }
    285             else
    286                 Result.Add(value.bstrVal);//
    287             m_pRecordset->MoveNext();
    288         }
    289         m_pRecordset->Close();
    290         return TRUE;
    291     }
    292     else
    293     {
    294         m_pRecordset->Close();
    295         return FALSE;
    296     }
    297 }
    298 
    299 BOOL CPData::SelectMulitCol(CString strSql,CStringArray& Result)
    300 {
    301     if(Select(strSql)!=0)
    302     {
    303         Result.RemoveAll();
    304         _variant_t value;
    305         for(int i=0;i<m_nResultRow;i++)
    306         {   
    307             for(int j=0;j<m_nResultCol;j++)
    308             {
    309                 value=m_pRecordset->Fields->Item[(long)(/*i*m_nResultCol+*/j)]->Value;
    310                 if(value.vt==3||value.vt==14)
    311                 {
    312                     CString strTrans;
    313                     strTrans.Format("%ld",value.intVal);
    314                     Result.Add(strTrans);
    315                 }
    316                 else
    317                     if(value.vt==7)
    318                     {
    319                         COleDateTime time = value.date;
    320                         CString strTemp;
    321                         strTemp.Format("%d-%d-%d %s",time.GetYear(),time.GetMonth(),time.GetDay(),time.Format("%H:%M:%S"));
    322                         Result.Add(strTemp);
    323                     }
    324                     else
    325                         Result.Add(value.bstrVal);//
    326             }
    327             m_pRecordset->MoveNext();
    328         }
    329         m_pRecordset->Close();
    330         return TRUE;
    331     }
    332     else
    333     { 
    334         m_pRecordset->Close();
    335         return FALSE;
    336     }
    337 }
    338 
    339 //打开整张表
    340 BOOL CPData::OpenTable(CString strTable)
    341 {
    342     try
    343     {
    344         m_nResultCol=0;
    345         m_nResultRow=0;  
    346         m_pRecordset->CursorLocation=adUseClient;    //设置游标位置,设置为客户端形式,否则GetRecordCount()返回值不对
    347         m_pRecordset->Open(_variant_t(strTable),_variant_t((IDispatch *)m_pConnection,true),adOpenDynamic,adLockOptimistic,adCmdTable);
    348         m_nResultCol = m_pRecordset->Fields->GetCount();//得到查询结果的列数
    349         m_nResultRow = m_pRecordset->GetRecordCount();  //得到查询结果的行数
    350     }
    351     catch(_com_error&e)
    352     {  
    353         AfxMessageBox(e.Description()+"E");
    354         return FALSE;
    355     }
    356     return TRUE;
    357 }
    358 
    359 BOOL CPData::OpenTable(CString strTable,CStringArray& Result)
    360 {
    361     if(OpenTable(strTable)!=0)
    362     {
    363         Result.RemoveAll();
    364         _variant_t value;
    365         for(int i=0;i<m_nResultRow;i++)
    366         {   
    367             for(int j=0;j<m_nResultCol;j++)
    368             {
    369                 value=m_pRecordset->Fields->Item[(long)(/*i*m_nResultCol+*/j)]->Value;
    370                 if(value.vt==3||value.vt==14)
    371                 {
    372                     CString strTrans;
    373                     strTrans.Format("%ld",value.intVal);
    374                     Result.Add(strTrans);
    375                 }
    376                 else
    377                     if(value.vt==7)
    378                     {
    379                         COleDateTime time = value.date;
    380                         CString strTemp;
    381                         strTemp.Format("%d-%d-%d %s",time.GetYear(),time.GetMonth(),time.GetDay(),time.Format("%H:%M:%S"));
    382                         Result.Add(strTemp);
    383                     }
    384                     else
    385                         Result.Add(value.bstrVal);//
    386             }
    387             m_pRecordset->MoveNext();
    388         }
    389         m_pRecordset->Close();
    390         return TRUE;
    391     }
    392     else
    393     {
    394         return FALSE;
    395     }
    396 }
    397 
    398 /////////////////////////////////////////////////////////////////////////////
    399 ///关闭结果集
    400 /////////////////////////////////////////////////////////////////////////////
    401 void CPData::CloseRecordset()
    402 {
    403     if(m_pRecordset->State != adStateClosed)
    404         m_pRecordset->Close();
    405 }
    406 BOOL CPData::ExecuteTrans(CStringArray& aSql)
    407 {
    408     try{
    409         int nNum = aSql.GetSize();
    410         m_pConnection->BeginTrans(); 
    411         for(int i=0;i<nNum;i++)
    412         {
    413             CString strSql = aSql.GetAt(i);  
    414             m_pConnection->Execute((_bstr_t)aSql.GetAt(i),NULL,adCmdText);
    415         }
    416         m_pConnection->CommitTrans(); 
    417         return TRUE;
    418     }
    419     catch(_com_error& e)
    420     {
    421         m_pConnection->RollbackTrans();  
    422         AfxMessageBox(e.Description()+"F");
    423         return FALSE;
    424     } 
    425 }
  • 相关阅读:
    天梯赛5-12 愿天下有情人都是失散多年的兄妹 【dfs】
    poj2718 Smallest Difference【贪心】
    HDU problem 5635 LCP Array【思维】
    codeforces 782C Andryusha and Colored Balloons【构造】
    HDU 4278 Faulty Odometer【进制转换】
    codeforces B. The Meeting Place Cannot Be Changed【二分】
    POJ 3264 Balanced Lineup 【线段树】
    HDU 1850
    CodeForces-714C
    HDU Problem 1247 Hat's Words 【字典树】
  • 原文地址:https://www.cnblogs.com/cnmyp/p/2624369.html
Copyright © 2011-2022 走看看