void CMyDlg::OnButton1()
{
// TODO: Add your control notification handler code here
if (AfxOleInit())//初始化OLE
{
_ConnectionPtr m_pConnection;//聲明一個鏈接對象
_RecordsetPtr m_pRecordset;
HRESULT hr;
try{
hr = m_pConnection.CreateInstance("ADODB.Connection"); //建立鏈接
if(SUCCEEDED(hr))//判斷是否鏈接成功
{
MessageBox("指針鏈接成功!");
m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb","","",adModeUnknown);//打開數據庫
_variant_t RecordsAffected;//聲明返回被修改的條目數
CString strSQL;//SQL字符串語句
strSQL.Format("insert into d1(name) values('%s')","正月龍");
m_pRecordset = m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);//操做數據庫
MessageBox("數據加入成功!");
//m_pRecordset->Close();
m_pRecordset = m_pConnection->Execute("select count(*) from d1",&RecordsAffected,adCmdText);//返回總條目數
_variant_t vIndex = (long)0;
_variant_t vCount = m_pRecordset->GetCollect(vIndex);//取得第一個字段的整數值放入vCount變量
CString str;
str.Format("總共有%d條數據",vCount.lVal);
MessageBox(str);
m_pRecordset = m_pConnection->Execute("select * from d1",&RecordsAffected,adCmdText);
//m_pRecordset->MoveNext();
//m_pRecordset->MoveNext();
_variant_t vIndex1 = (long)0;
_variant_t vCount1 = m_pRecordset->GetCollect(vIndex1);//取得第一個字段的字符串值放入vCount1變量
CString str1;
str1 = vCount1.bstrVal;
MessageBox("第一個字段內容是:"+str1);
m_pRecordset->Close();
}
}catch(_com_error e)
{
CString str;
str.Format("數據庫鏈接失敗\r\n錯誤信息:%s",e.ErrorMessage());
MessageBox(str);
}
//MessageBox("初始化 OLE 成功!");
}else
MessageBox("初始化 OLE 失敗");
}