您的位置:首页 > 数据库

在mfc使用ADO对象进行数据库的交互

2014-07-06 10:33 513 查看
   前一段时间自从自己看了mfc之后就一直想把数据库,线程,进程这一块先做个铺垫总结一些,无耐,最近忙着课程设计和期末考试,也就没管它!今天想起来,决定总结一下,也算是为以后的学习做个铺垫吧!因为,我知道新知识很容易忘记,学的快,丢的也快!所以不断的总结是一个好习惯!好吧!进入正题!

   我的编译环境是SQL server2012和vs2012。

   数据库交互是一个非常重要的东西,尤其是很多东西都放在数据库中,和数据库交互也是软件设计中的一个重要的环节!

我目前掌握的也就是使用ActiveX控件和ADO对象进行数据库交互,前者比较简单,基本上不用敲代码,改一改参数就行了!关键是后者!其实也不是很难,就是一个很固定的流程!这里先抛开数据库知识不谈!就说怎么交互!

1:创建应用程序框架。其实也就是做一个简单的界面,在mfc中很方便,知道怎么添加变量·类,怎么关联变量也就差不多了!

2:在stdafx.h头文件中添加以下代码:

#import "C:\\Program Files\\Common Files\\System\\ado\\msado15.dll" no_namespace rename("EOF","EndOfFile")

要注意的地方在上篇博文中已说明!

3:初始化COM 环境。有这一步是因为:ADO是建立在OLE DB基础之上的,而OLE DB是基于COM接口的,COM组件的使用之前是需要初始化的!

初始化的方法:在OnInitDialog函数中添加:

    ::CoInitialize(NULL);//前面加上“::”表示调用系统的方法。而不是封装好了的方法。

4:  定义ADO对象:其实也就是定义几个指针变量,然后实例化:

   _ConnectionPtr m_pConn;//;连接对象的指针

   _RecordsetPtr m_pRs;//记录集对象的指针

   _CommandPtr m_pComm;//命令对象的指针

   然后实例化:

        m_pConn.CreateInstance(__uuidof(Connection));

        m_pRs.CreateInstance(__uuidof(Recordset));

        m_pComm.CreateInstance(__uuidof(Command));

5:接着就是连接数据库了:

  m_pConn->Open("driver={SQL Server};Server=127.0.0.1;DATABASE=Student;","sa","root",adModeUnknown);

  其实前几个参数都可以看懂;就是最后一个参数,让人有点莫名其妙。右键,difine查看。

ConnectModeEnum
{
adModeUnknown = 0,
adModeRead = 1,
adModeWrite = 2,
adModeReadWrite = 3,
adModeShareDenyRead = 4,
adModeShareDenyWrite = 8,
adModeShareExclusive = 12,
adModeShareDenyNone = 16,
adModeRecursive = 4194304
};
每一个数字表示的意义如下:
0:  Default. Indicates that the permissions have not yet been set or cannot be determined.
1:  Indicates read-only permissions.
2:  Indicates write-only permissions.
3.  Indicates read/write permissions.
4   Prevents others from opening a connection with read permissions.
8.  Prevents others from opening a connection with write permissions.
12. Prevents others from opening a connection.
16. Allows others to open a connection with any permissions. Neither read nor write access can be denied to others.
4194304. Used in conjunction with the other <em>*ShareDeny*</em> values (<strong>adModeShareDenyNone</strong>, <strong>adModeShareDenyWrite</strong>, or <strong>adModeShareDenyRead</strong>) to propagate sharing restrictions to all sub-records of the current <strong>Record</strong>. It has no affect if the <strong>Record</strong> does not have any children. A run-time error is generated if it is used with <strong>adModeShareDenyNone</strong> only. However, it can be used with <strong>adModeShareDenyNone</strong> when combined with other values. For example, you can use "<strong>adModeRead</strong> Or <strong>adModeShareDenyNone</strong> Or <strong>adModeRecursive</strong>".

6.然后就是检索记录,编辑记录(添加,更新,删除)等!具体的实例看下一篇

7.释放ADO对象。

  在OnDestroy()函数中,添加:

  CDialog::OnDestroy();

  m_pConn->Close();//关闭数据库连接

  m_pRs = NULL;//释放记录集指针

  m_pConn = NULL;//释放连接对象指针

  m_pComm = NULL;//释放命令对象指针

  ::CoUninitialize();//释放ADO对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息