NoteBook开发手记(二)

     NoteBook的重点也是难点的地方在数据库的使用。当我需要把编辑好的内容存储到数据库,当打开软件,读出数据的时候也需要访问数据库。所以和数据库的交互是本程序的精髓,然而在设计数据库的时候却遇到了麻烦。

 

    当需要浏览或者创建新的记录的时候就需要通过树型控件来进行选择,该树可以这样生成

 |--根类别

 |       |

 |       |----子类别                                                 

 |       |           |

 |       |           |----子记录

 |       |                 

 |       |----子记录

 |

 |--根记录

 

也就是说我们的数据库存储要根据树型的构造来存储数据,想了很久也得不到答案。后来,今天问了一个搞了10多年数据库的同事,终于得到了一种比较满意的答案。建立一张表,然后建一个字段“父ID”,每个子类别或者子记录对应一个ID号(这个ID号是自动的),根类别或者根记录的“父ID”就为0,也即空。这样就可以把整棵数的内容存储到数据库了,当然,还需要其他的一些字段如:标题、内容、日期,等等和记录相关的字段。

 

    好了,有了数据库,就可以封装一个类来进行数据库的添加、删除、修改操作了。利用ADO的连接方式,下面给出了这个类的具体代码:

  1. #pragma once
  2. #include <vector>
  3. #include "StdAfx.h"
  4. using std::vector;
  5. // 数据成员
  6. class Item
  7. {
  8. public:
  9.     int     m_nID;              // ID
  10.     CString m_strTitle;         // 标题   
  11.     CString m_strTime;          // 时间
  12.     CString m_strKey;           // 关键字
  13.     CString m_strContext;       // 内容
  14.     CString m_strMark;          // 备注
  15.     int     m_nParentID;        // 父亲ID
  16. };
  17. class CDataBase
  18. {
  19. public:
  20.     CDataBase(CString strName);
  21.     virtual ~CDataBase(void);
  22. public:
  23.     void    Init();             // 初始化数据库
  24.     void    Destroy();          // 销毁数据库连接
  25. private:
  26.     _ConnectionPtr  m_pConnection;  // 连接数据库指针
  27.     _CommandPtr     m_pCommand;     // 命令集指针
  28.     _RecordsetPtr   m_pRecordset;   // 记录集指针
  29.     CString         m_strDatabaseName;// 数据库名称
  30. 保存所有的数据
  31.     BOOL    Load();             // 加载所
  32. public:
  33.     
  34.     BOOL    Add(Item &item);    // 添加一条记录
  35.     BOOL    Delete(int nID);    // 删除一条记录
  36.     //BOOL  Modify()
  37. };
  38. vector<Item>    m_vecItem;  // 数据容器
  39.     // 接口
  40. public:
  41.     BOOL    Save();             // 有的数据
    1. #include "StdAfx.h"
    2. #include "DataBase.h"
    3. CDataBase::CDataBase(CString strName)
    4.     : m_strDatabaseName(strName)
    5.     , m_pConnection(NULL)
    6.     , m_pCommand(NULL)
    7.     , m_pRecordset(NULL)
    8. {
    9.     Init();
    10. }
    11. CDataBase::~CDataBase(void)
    12. {
    13.     Destroy();
    14. }
    15. // 初始化数据库
    16. void CDataBase::Init()
    17. {
    18.     m_pConnection.CreateInstance(__uuidof(Connection));
    19.     try                 
    20.     {   
    21.         // 打开本地Access库NoteBook.mdb
    22.         CString strSQL=_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=")+m_strDatabaseName+_T(".mdb");
    23.         m_pConnection->Open(_bstr_t(strSQL),_T(""),_T(""),adModeUnknown);
    24.         m_pCommand.CreateInstance(__uuidof(Recordset));
    25.         m_pRecordset.CreateInstance(__uuidof(Recordset));
    26.         try
    27.         {
    28.             // 获取所有字段数据
    29.             m_pRecordset->Open(_T("SELECT * FROM NoteBook"),m_pConnection.GetInterfacePtr(),
    30.                 adOpenDynamic,adLockOptimistic,adCmdText);
    31.         }
    32.         catch(_com_error &e)
    33.         {
    34.             AfxMessageBox(e.ErrorMessage());
    35.             return;
    36.         }
    37.     }
    38.     catch(_com_error &e)
    39.     {
    40.         
    41.         AfxMessageBox(e.ErrorMessage());
    42.         return;
    43.     }      
    44.     
    45. }
    46. // 销毁释放资源
    47. void CDataBase::Destroy()
    48. {
    49.     if( m_pRecordset!=NULL )
    50.     {
    51.         m_pRecordset->Close();
    52.         m_pRecordset.Release();
    53.         m_pRecordset=NULL;
    54.     }
    55.     if( m_pCommand!=NULL )
    56.     {
    57.         m_pCommand.Release();
    58.         m_pCommand=NULL;
    59.     }
    60.     if( m_pConnection->State )
    61.     {
    62.         m_pConnection->Close();
    63.         m_pConnection.Release();
    64.         m_pConnection= NULL;  
    65.     }
    66.     
    67. }
    68. // 加载数据库数据
    69. BOOL CDataBase::Load()
    70. {
    71.     if( m_pRecordset==NULL )
    72.         return FALSE;
    73.     _variant_t varID,varTitle,varTime,varKey,varContext,varMark,varParentID;
    74.     Item item;
    75.     try
    76.     {
    77.         if( !m_pRecordset->BOF )
    78.             m_pRecordset->MoveFirst();
    79.         else
    80.         {
    81.             AfxMessageBox(_T("表内数据为空"));
    82.             return FALSE;
    83.         }
    84.         // 读出库中各字段数据
    85.         while( !m_pRecordset->adoEOF )
    86.         {
    87.             varID = m_pRecordset->GetCollect(_T("ID"));
    88.             if(varID.vt != VT_NULL)
    89.                 item.m_nID = (long)(varID);
    90.             varTitle = m_pRecordset->GetCollect(_T("标题"));
    91.             if(varTitle.vt != VT_NULL)
    92.                 item.m_strTitle = (LPCSTR)_bstr_t(varTitle);
    93.             varTime = m_pRecordset->GetCollect(_T("日期"));
    94.             if(varTime.vt != VT_NULL)
    95.                 item.m_strTime = (LPCSTR)_bstr_t(varTime);
    96.             varKey = m_pRecordset->GetCollect(_T("关键字"));
    97.             if(varKey.vt != VT_NULL)
    98.                 item.m_strKey = (LPCSTR)_bstr_t(varKey);
    99.             varContext = m_pRecordset->GetCollect(_T("内容"));
    100.             if(varContext.vt != VT_NULL)
    101.                 item.m_strKey = (LPCSTR)_bstr_t(varContext);
    102.             varMark = m_pRecordset->GetCollect(_T("备注"));
    103.             if(varMark.vt != VT_NULL)
    104.                 item.m_strMark = (LPCSTR)_bstr_t(varMark);
    105.             varParentID = m_pRecordset->GetCollect(_T("父亲"));
    106.             if(varParentID.vt != VT_NULL)
    107.                 item.m_nParentID = (long)(varParentID);
    108.             // 送到容器
    109.             m_vecItem.push_back(item);
    110.             // 移动到下一条记录
    111.             m_pRecordset->MoveNext();
    112.         }
    113.     }
    114.     catch(_com_error &e)
    115.     {
    116.         AfxMessageBox(e.ErrorMessage());
    117.         return FALSE;
    118.     }
    119.     return TRUE;
    120. }
    121. // 存储到数据库
    122. BOOL CDataBase::Save()
    123. {
    124.     if( m_pRecordset==NULL )
    125.         return FALSE;
    126.     try
    127.     {
    128.         m_pCommand->ActiveConnection = m_pConnection;
    129.         m_pCommand->CommandText=_T("TRUNCATE TABLE NoteBook");
    130.         m_pCommand->Execute(NULL,NULL,adCmdText);       // 执行SQL语句
    131.         // 写入各字段值
    132.         m_pRecordset->AddNew();
    133.         for(vector<Item>::iterator iter=m_vecItem.begin(); iter!=m_vecItem.end(); ++iter)
    134.         {
    135.             m_pRecordset->PutCollect(_T("标题"), _variant_t(iter->m_strTitle));
    136.             m_pRecordset->PutCollect(_T("日期"), _variant_t(iter->m_strTime));
    137.             m_pRecordset->PutCollect(_T("关键字"), _variant_t(iter->m_strKey));
    138.             m_pRecordset->PutCollect(_T("内容"), _variant_t(iter->m_strContext));
    139.             m_pRecordset->PutCollect(_T("备注"), _variant_t(iter->m_strMark));
    140.             m_pRecordset->PutCollect(_T("父亲"), _variant_t(iter->m_nParentID));
    141.         }
    142.         m_pRecordset->Update();
    143.     }
    144.     catch(_com_error *e)
    145.     {
    146.         AfxMessageBox(e->ErrorMessage());
    147.         return FALSE;
    148.     }    
    149.     return TRUE;
    150. }
    151. // 增加记录
    152. BOOL CDataBase::Add(Item &item)
    153. {
    154.     if( m_pRecordset==NULL )
    155.         return FALSE;
    156.     // 向容器添加记录
    157.     m_vecItem.push_back(item);
    158.     try
    159.     {
    160.         // 向数据库增加记录
    161.         m_pRecordset->AddNew();
    162.         
    163.         m_pRecordset->PutCollect(_T("标题"), _variant_t(item.m_strTitle));
    164.         m_pRecordset->PutCollect(_T("日期"), _variant_t(item.m_strTime));
    165.         m_pRecordset->PutCollect(_T("关键字"), _variant_t(item.m_strKey));
    166.         m_pRecordset->PutCollect(_T("内容"), _variant_t(item.m_strContext));
    167.         m_pRecordset->PutCollect(_T("备注"), _variant_t(item.m_strMark));
    168.         m_pRecordset->PutCollect(_T("父亲"), _variant_t(item.m_nParentID));
    169.         
    170.         m_pRecordset->Update();
    171.     }
    172.     catch(_com_error *e)
    173.     {
    174.         AfxMessageBox(e->ErrorMessage());
    175.         return FALSE;
    176.     }    
    177.     return TRUE;
    178. }
    179. // 删除指定记录
    180. BOOL CDataBase::Delete(int nID)
    181. {
    182.     try
    183.     {
    184.         CString strSQL;
    185.         strSQL.Format(_T("DELETE FROM NoteBook WHERE ID=%d"),nID);
    186.         m_pCommand->ActiveConnection = m_pConnection;
    187.         m_pCommand->CommandText=(_bstr_t)strSQL;
    188.         m_pCommand->Execute(NULL,NULL,adCmdText);       // 执行SQL语句
    189.     }
    190.     catch(_com_error *e)
    191.     {
    192.         AfxMessageBox(e->ErrorMessage());
    193.         return FALSE;
    194.     }  
    195.     return TRUE;
    196. }

    这样,我们的操作数据库就简单了。就可以通过树型控件来进行数据库的访问操作了!

 

    后记:在测试这个类的时候,发现退出程序会出现recordset异常,察看了调用堆栈,居然说recordset的Close方法错误?

My GOD! 怎么可能呢?recordset智能指针时需要先Close再Release的嘛!,后来检查Destroy函数,才发现原来是connection指针已经释放了,导致recordset指针出错!把释放顺序改成先recordset再connection就没问题了~具体什么原因,也不想追踪了,但是一定记得--释放recordset指针的时候一定要赶在connection指针释放前!!

你可能感兴趣的:(sql,数据库,null,delete,存储,Access)