Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1059992
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: 数据库开发技术

2009-08-31 15:02:37

网络上找到的资料,先mark下,随后再试试
1、在stdafx.h文件最后(即#endif // _AFX_NO_AFXCMN_SUPPORT下面)添加:
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")

2、初始化COM:
AfxOleInit();//这行代码要放在功能执行前,如果是基于对话框建立的程序,那就放在第一个对话框类的OnInitDialog()函数的return TRUE;前

3、在用到数据库的地方:
_ConnectionPtr m_pConnection;///声明数据库连接变量
_RecordsetPtr m_pRecordset;///声明数据库集合变量
CString strCn;
strCn.Empty();

(1)连接数据库
HRESULT hr;
try
{
_variant_t RecordsAffected;
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("DSN=test;UID=;PWD=;","","",adModeUnknown);///连接数据库
}
}
catch( _com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
}

(2)通过SQL读数据
CString sql;
try
{
m_pRecordset.CreateInstance("ADODB.Recordset");
m_pRecordset->Open((_variant_t)sql,_variant_t((IDispatch*)m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
}
catch(_com_error e)///捕捉异常
{
CString errorMessage = e.ErrorMessage();
AfxMessageBox("读取数据时出错:"+sql+errorMessage);///显示错误信息
}

(3)通过sql语句添加、修改、删除记录
_variant_t RecordsAffected;

try
{
m_pConnection->Execute((_bstr_t)Sql,&RecordsAffected,adCmdText);
}
catch(_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
}
阅读(3124) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~