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

阅读更多
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,sql)