vs2008 连接SQL Server2005 express 或ACCESS数据库

SQL server配置按我的另一篇文章即可搞定。环境配置好后,按又下方法即可连接到任一数据库,对其进行操作。

主要步骤为:

1. 在stdafx.h头文件末尾中加入

#import "C:\Program Files\Common Files\System\ado\msado15.dll"  named_guids rename("EOF","adoEOF")
#pragma warning(default:4146)
using namespace ADODB;

 

//如果你的文件路径不同,做相应改变即可,但每个有VS环境的人都有msado15.dll这个文件。

//named_guids rename()语句改变数据集的“EOF”名称为别名“adoEOF”,又便在程序中使用,你也可又不用改变。

2、使用定义_ConnectionPtr定义数据库连接句柄

3、使用定义_ConnectionPtr.reateInstance()方法初始化

4、使用_RecordsetPtr,或_commandPtr连接_connectionPtr定义的连接,然后即可访问数据

 

 

代码如下:

 

CString  strConnect="Provider=SQLOLEDB;Server=.\\xxxxxxxxx or (xxx.xxx.xxx.xxx, port);Database=xxxxx;uid=xxxxxx;pwd=xxxxxxxx" 

//如果连接ACCSS DATABASE 则

CString   strConnect="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=xxxxx;Persist Security Info=False"

/

_ConectionPtr MyConnect;

HRESULT hr=MyConnect.CreateInstance(_uuidof(Connection));
 if(FAILED(hr))
 {
  return FALSE;
 }
 _bstr_t strConnect=IniString;//
 
 try
 {
  MyConnect->CursorLocation=adUseServer ;
  MyConnect->Open(strConnect,"","",NULL);
 }
 catch (_com_error &e)
 {
  ::MessageBox(NULL,e.Description(),L"Warning",MB_OK | MB_ICONWARNING);
  return FALSE;
 }

_RecordsetPtr m_pRecordset;


 _CommandPtr m_pCommand;

 //  if(FAILED(m_pRecordset.CreateInstance( __uuidof( Recordset ))))
 //  {
 //   
 //   ::MessageBox(NULL,L"Can not CreateInstance of Record",L"Warning",MB_OK | MB_ICONWARNING);
 //   return FALSE;
 //  }

 if(FAILED(m_pCommand.CreateInstance( __uuidof( Command ))))
 {

  ::MessageBox(NULL,L"Can not Open the Recordset",L"Warning",MB_OK | MB_ICONWARNING);
  return NULL;
 }

 m_pCommand->put_ActiveConnection(_variant_t((IDispatch *)MyConnect));

 m_pCommand->CommandText =SQLstring;

 //m_pCommand->CommandText="INSERT INTO OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c://XXX.mdb;Persist Security Info=False')...TB_FILM SELECT * FROM db1";
 try
 {
  m_pRecordset=m_pCommand->Execute(NULL,NULL,adCmdText);
 }

 catch (_com_error &e)
 {
  ::MessageBox(NULL,e.Description(),L"Warning",MB_OK | MB_ICONWARNING);
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值