1void CTestdbDlg::OnOK()
2{
3 // TODO: Add extra validation here
4 //AfxOleInit();
5 CoInitialize(NULL); //初始化
6 //打开数据库
7 _ConnectionPtr m_pConnection;
8 try
9 {
10 m_pConnection.CreateInstance("ADODB.Connection");
11 // ASSERT(m_pConnection != NULL);
12 _bstr_t strConnect="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb;Persist Security Info=False";
13 m_pConnection->ConnectionTimeout=5; //设置超时时间为5秒
14 m_pConnection->Open(strConnect,"","",adModeUnknown);
15 }
16 catch(_com_error e)
17 {
18 AfxMessageBox(e.ErrorMessage());
19 }
20 _RecordsetPtr m_pRecordset; //一个指向Recordset对象的指针
21 //查询
22 CString sql="select sno From [sn] ";
23 try
24 {
25 m_pRecordset.CreateInstance(__uuidof(Recordset));
26 m_pRecordset->Open((_variant_t)sql,_variant_t((IDispatch*)m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
27 while(!m_pRecordset->GetadoEOF())
28 {
29 _variant_t var;
30 var=m_pRecordset->GetCollect("sno");
31 if(var.vt != VT_NULL)
32 {
33 CString strValue =(LPCSTR)_bstr_t(var);
34 MessageBox(strValue);
35 }
36 m_pRecordset->MoveNext();
37 }
38 }
39 catch(_com_error e)/**////捕捉异常
40 {
41 AfxMessageBox(e.ErrorMessage());
42 AfxMessageBox(e.Source());
43 AfxMessageBox(e.Description());
44 }
45 //更新
46 _bstr_t sql2="update [sn] set name='sss' where sno=3";
47 _variant_t RecordsAffected;
48 m_pConnection->Execute(sql2,&RecordsAffected,adCmdText);
49 m_pRecordset->Close();/**////关闭记录集
50 m_pConnection->Close();/**////关闭连接
51// AfxOleTerm();
52 CoUninitialize();
53
54}
在连接数据库之前要添加#import "C:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename("EOF","adoEOF")
路径根据本机设置修改
rename("EOF","adoEOF") //重新命名