如何在VS2005中连接数据库 (ado)

这里连接数据库的模式是ado,至于ado和odbc数据连接的区别,可以看这位网友的:http://blog.csdn.net/mythic_y/article/details/6019758


1.1打开microsoft SQL server 2005 下的sql server management studio 新建一个数据库,名称叫:LekaDemo  (提示:如果没有找到 sql server management studio的,需要自己重新安装以下 )
打开的界面如下:
1.2点击"连接"后,进入到以下界面:

1.3右击“数据库”,就可以创建一个新的数据库了。这里新建的数据库名称为LekaDemo

1.4.在数据库 LekaDemo中新建一个表命名为AdoTestTable

*******************************************************************************
2.1.首先打开vs2005,新建一个MFC应用程序的工程。
2.2在工程中,找到头文件stdafx.h ,在这里添加以下的代码:
 
   
 
      
#import "C://Program Files//Common Files//System//ado//msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")

2.3.在xxDlg.h中添加以下变量
 
   
_RecordsetPtr m_pRecordset;
_ConnectionPtr m_pConnection;
_CommandPtr m_pCommand; // 记录

2.4.在xxdlg.cpp的OnInitDialog()函数中添加以下代码:
 
   
if (!AfxOleInit())//初始化OLE/COM库环境
{
AfxMessageBox(_T("OLE初始化出错!"));
return FALSE;
}
try
{
m_pConnection.CreateInstance("ADODB.Connection");
 
//SQL 登录模式 xieijiah 20161006
_bstr_t strConnect = "Provider=SQLOLEDB.1;Data Source=WIN-2CFAN5CUF3F\\SQLEXPRESS;Initial Catalog=LekaDemo;User ID=sa;PWD=sa";
//window登录连接方式 xiejiah 20161006
// _bstr_t strConnect = "Provider=SQLOLEDB.1;Integrated Security = SSPI;Persist Security Info = FALSE;Data Source=WIN-2CFAN5CUF3F\\SQLEXPRESS;Initial Catalog=LekaDemo;";
//设置延时时间为5秒 xieijiah 20161006
m_pConnection->ConnectionTimeout=5;
m_pConnection->Open(strConnect,"","",adModeUnknown);
AfxMessageBox(_T("连接成功"));
}
catch(_com_error e)
{
AfxMessageBox(_T("连接失败"));
}

2.5至此一个新的ado连接数据库的程序就新建好了。


3.具体实现的过程,可以看工程代码:
http://download.csdn.net/detail/xjh0918/9646771

猜你喜欢

转载自blog.csdn.net/XJH0918/article/details/52749285
ADO