您的位置:首页 > 数据库

ADO技术连接SQL数据库

2015-09-11 10:48 148 查看
一、初始化com 库

在stdafx.h文件中添加下面代码

#import "c:\program files\commonfiles\system\ado\msado15.dll" no_namespacerename("EOF","adoEOF")

//作用是 系统会为我们生成msado15.tlh,ado15.tli两个C++头文件来定义ADO库然后在你的 ****(你的项目名).h 文件中添加stdafx.h 头文件(点击保存才不报错,不知道为啥,但是等一会就不会报错了)这样就可以使用三个智能指针了:

{_ConnectionPtr 连接指针

_RecordsetPtr记录集指针

_CommandPtr 命令指针}

二、在你的项目名.h 文件中声明链接指针(或在项目名Dlg.h 中都声明一下)

public:

_ConnectionPtr m_pConnection; // 连接对象指针

_RecordsetPtrm_pRecordset; //记录对象指针

_CommandPtrm_pCommand; //定义命令指针

三、用AfxOleInit()来初始化COM库,在项目名称Dlg.cpp 文件中,找到InitInstance() 重数,

添加:

例如:

BOOL CADOTest1App::InitInstance()

{

AfxOleInit();

try

{

m_pConnection.CreateInstance(_uuidof(Connection));//创建Connection对象

m_pRecordset.CreateInstance(_uuidof(Recordset)); //初始化m_pRecordset

}

catch(_com_error e1)

{

AfxMessageBox(_T("创建 ado 连接错误!!!"));

return FALSE;

}

try{ m_pConnection->Open("driver={SQLServer};Server=127.0.0.1;DATABASE=ado;UID=sa;PWD=123456","","",adModeUnknown);

// ado 是库的名字

}

catch(_com_error e2) //捕捉异常

{

AfxMessageBox(_T("连接数据库失败!请确认数据库连接路径!!!"));

return FALSE;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: