当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

MFC中使用ado技术操作数据库

发表于: 2015-07-03   作者:你不认识的休道人   来源:转载   浏览:
摘要: 1.在stdafx.h中导入ado动态链接库 #import"C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","end")2.在CTestApp文件的InitInstance()函数中domodal之前写::CoIniti
1.在stdafx.h中导入ado动态链接库
#import"C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","end")
2.在CTestApp文件的InitInstance()函数中domodal之前写::CoInitialize(NULL);程序结束时CoUninitialize();
3.CTestDlg.h中添加:
_ConnectionPtr connection;
_RecordsetPtr record;

初始化工作在cpp文件的BOOL CTestDlg::OnInitDialog()函数中完成:
try{ } catch(_com_error e){ e.Description() }
connection.CreateInstance("ADODB.Connection");
bstr_t strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\\StudyPoems.accdb;Persist Security Info=False";
connection->Open(strConnect,"","",adModeUnknown);

执行OnCancle()时释放连接:connection->Close();
4.查询记录
CString sql = "select * from studentstable";
	record.CreateInstance(__uuidof(Recordset));
	record->Open(_bstr_t(sql),connection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
	CString num,pass,progress;
	while(!record->end)
	{
		num = (char *)(_bstr_t)record->GetCollect("num");
		pass = (char *)(_bstr_t)record->GetCollect("password");
		progress = (char *)(_bstr_t)record->GetCollect("progress");

		m_list.InsertItem(0,num,0);
		m_list.SetItemText(0,1,pass);
		m_list.SetItemText(0,2,progress);
		record->MoveNext();
	}
	//关闭记录集
	record->Close();

5.修改记录
CString sql = "update studentstable set [password] = '201234' where num = '100003'";
	connection->Execute((_bstr_t)sql,NULL,adCmdText);
6.增加记录
CString cmdstr = "select * from studentstable";
	//利用ado对象添加记录
	record.CreateInstance(_uuidof(Recordset));
	record->Open(_bstr_t(cmdstr),connection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
	record->AddNew();
	CString num = "100003";
	CString pass = "300001";
	CString progress = "1";
	record->PutCollect("num",(_bstr_t)num);
	record->PutCollect("password",(_bstr_t)pass);
	record->PutCollect("progress",(_bstr_t)progress);

	record->Update();	
	record->Close();

7.删除记录
CString sql = "delete from studentstable where num = '100003'";
	connection->Execute((bstr_t)sql,NULL,adCmdText);

MFC中使用ado技术操作数据库

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号