// 假設(shè)刪除第二條記錄}
m_pRecordset->MoveFirst();
m_pRecordset->Move(1);
m_pRecordset->Delete(adAffectCurrent);// 參數(shù)adAffectCurrent為刪除當(dāng)前記錄
m_pRecordset->Update();
hr = m_pConnect.CreateInstance("ADODB.Connection");if(SUCCEEDED(hr)){
CString dd;dd.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",file);hr = m_pConnect->Open((_bstr_t)dd,"","",adModeUnknown);pSet = m_pConnect->OpenSchema(adSchemaTables);while(!(pSet->adoEOF)){
//獲取表格_bstr_t table_name = pSet->Fields->GetItem("TABLE_NAME")->Value;_bstr_t table_type = pSet->Fields->GetItem("TABLE_TYPE")->Value; //獲取表格類型//過濾一下,只輸出表格名稱,其他的省略if ( strcmp(((LPCSTR)table_type),"TABLE")==0){
CString tt;tt.Format("%s",(LPCSTR)table_name);AfxMessageBox(tt);
}pSet->MoveNext();
}pSet->Close();
}m_pConnect->Close();
CString errormessage;errormessage.Format("連接數(shù)據(jù)庫失敗!rn錯(cuò)誤信息:%s",e.ErrorMessage());AfxMessageBox(errormessage);return -1;
strColName=bstrColName;nameField = strColName;m_FieldsList.AddString(nameField);
adOpenUnspecified = -1,///不作特別指定adOpenForwardOnly = 0,///前滾靜態(tài)光標(biāo)。這種光標(biāo)只能向前瀏覽記錄集,比如用MoveNext向前滾動(dòng),這種方式可以提高瀏覽速度。但諸如BookMark,RecordCount,AbsolutePosition,AbsolutePage都不能使用adOpenKeyset = 1,///采用這種光標(biāo)的記錄集看不到其它用戶的新增、刪除操作,但對于更新原有記錄的操作對你是可見的。adOpenDynamic = 2,///動(dòng)態(tài)光標(biāo)。所有數(shù)據(jù)庫的操作都會(huì)立即在各用戶記錄集上反應(yīng)出來。adOpenStatic = 3///靜態(tài)光標(biāo)。它為你的記錄集產(chǎn)生一個(gè)靜態(tài)備份,但其它用戶的新增、刪除、更新操作對你的記錄集來說是不可見的。
adLockUnspecified = -1,///未指定adLockReadOnly = 1,///只讀記錄集adLockPessimistic = 2,悲觀鎖定方式。數(shù)據(jù)在更新時(shí)鎖定其它所有動(dòng)作,這是最安全的鎖定機(jī)制adLockOptimistic = 3,樂觀鎖定方式。只有在你調(diào)用Update方法時(shí)才鎖定記錄。在此之前仍然可以做數(shù)據(jù)的更新、插入、刪除等動(dòng)作adLockBatchOptimistic = 4,樂觀分批更新。編輯時(shí)記錄不會(huì)鎖定,更改、插入及刪除是在批處理模式下完成。
CDialog::OnInitDialog();HRESULT hr;try{
hr = m_pConnection.CreateInstance("ADODB.Connection");/ //創(chuàng)建Connection對象if(SUCCEEDED(hr)){
hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4 .0;Data Source=test.mdb","","",adModeUnknown);///連接數(shù)據(jù)庫///上面一句中連接字串中的Provider是針對ACCESS2000環(huán)境的,對于ACCESS97,需要改為:Provider=Microsoft.Jet.OLEDB.3.51;
}
}catch(_com_error e)///捕捉異常{
CString errormessage;errormessage.Format("連接數(shù)據(jù)庫失敗!\r\n錯(cuò)誤信息:%s",e.ErrorMessage());AfxMessageBox(errormessage);///顯示錯(cuò)誤信息
}
vID = m_pRecordset->GetCollect(_variant_t((long)0));///取得第1列的值,從0開始計(jì)數(shù),你也可以直接給出列的名稱,如下一行vUsername = m_pRecordset->GetCollect("username");///取得username字段的值vOld = m_pRecordset->GetCollect("old");vBirthday = m_pRecordset->GetCollect("birthday");///在DEBUG方式下的OUTPUT窗口輸出記錄集中的記錄if(vID.vt != VT_NULL && vUsername.vt != VT_NULL && vOld.vt != VT_NULL && vBirthday.vt != VT_NULL)TRACE("id:%d,姓名:%s,年齡:%d,生日:%s\r\n",vID.lVal,(LPCTSTR)(_bstr_t)vUsername,vOld .lVal,(LPCTSTR)(_bstr_t)vBirthday);m_pRecordset->MoveNext();///移到下一條記錄
m_pRecordset->AddNew();///添加新記錄m_pRecordset->PutCollect("ID",_variant_t((long)(i+1 0)));m_pRecordset->PutCollect("username",_variant_t("葉利欽"));m_pRecordset->PutCollect("old",_variant_t((long)71) );m_pRecordset->PutCollect("birthday",_variant_t("193 0-3-15"));
void CAdoSTDlg::OnBtnbl()
{
// TODO: Add your control notification handler code here
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
CString sql;
sql.Format("select * from st order by No ASC");
_RecordsetPtr m_pRecordset;
m_pRecordset=m_AdoConn.GetRecordSet((_bstr_t)sql);
////////////////////////////////////////////////
int row,col,rowsum;
m_list.SetExtendedStyle(LVS_REPORT|LVS_EX_FULLROWSELECT|LVS_OWNERDRAWFIXED |LVS_EX_FLATSB|LVS_SHOWSELALWAYS|LVS_EX_HEADERDRAGDROP);
m_list.DeleteAllItems();
for (col=m_col;col>=0;col--)
m_list.DeleteColumn(col);
// for (i=0;i<m_pRecordset->Fields->Count;i++)
//m_list.InsertColumn(i,(const char *)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t((long)i))->Name));
rowsum=0;
while(!m_pRecordset->adoEOF)
{
rowsum++;
m_pRecordset->MoveNext();
}
m_pRecordset->MoveFirst();
for (row=0;row<rowsum;row++)
m_list.InsertItem(row,"row行",0);//不寫此句可能造成只顯示標(biāo)題行
for (col=0;col<m_pRecordset->Fields->Count;col++)
m_list.InsertColumn(col,(const char *)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t((long)col))->Name));
for(col=0;col<m_pRecordset->Fields->Count;col++)
m_list.SetColumnWidth(col,80);
CString str;
rowsum=0;
for(row=0;!m_pRecordset->adoEOF;row++)
{
for(col=0;col<m_pRecordset->Fields->Count;col++)
{
//m_list.SetItemText(i,j,(char*)
// ((_bstr_t) m_pRecordset->GetFields()->GetItem(_variant_t((long)j))->GetValue()));
// str.Format("%d行,%d列",row,col);
// m_list.SetItemText(row,col,str);
m_list.SetItemText(row,col,(char*)
((_bstr_t) m_pRecordset->GetFields()->GetItem(_variant_t((long)col))->GetValue()));// 行,列,內(nèi)容
}
m_pRecordset->MoveNext();
}
// m_pRecordset->MoveNext();
//
// }
m_col=m_pRecordset->Fields->Count;
//m_pRecordset->Close();
m_AdoConn.ExitConnect(); //ExitConnect 已包含m_pRecordset->Close();
}
void CAdoSTDlg::OnBtnadd()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if(m_id.IsEmpty())
{
MessageBox("此項(xiàng)不能為空!");
}
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
_bstr_t sql;
sql="select * from st order by No ASC";
_RecordsetPtr m_pRecordset;
m_pRecordset=m_AdoConn.GetRecordSet((_bstr_t)sql);
try
{
m_pRecordset->AddNew();
m_pRecordset->PutCollect("No",(_bstr_t)m_id);
m_pRecordset->PutCollect("Name",(_bstr_t)m_name);
m_pRecordset->PutCollect("Address",(_bstr_t)m_qita);
m_pRecordset->Update();
}
catch(...)
{
MessageBox("操作失敗");
return;
}
MessageBox("添加成功");
m_list.DeleteAllItems();
OnBtnbl(); //遍歷顯示
}
void CAdoSTDlg::OnBtnmod()
{
// TODO: Add your control notification handler code here
//**************************************************
UpdateData(TRUE);
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
_bstr_t sql;
CString strsql;
// strsql.Format("delete from st where no = 66%s",m_id);
strsql.Format("update st set Name = %s,Address = %s where No = %s",m_name,m_qita,m_id);
//sql="delete from st where No=66";
m_AdoConn.ExecuteSQL((_bstr_t)strsql);
//m_AdoConn.ExecuteSQL(sql);
m_AdoConn.ExitConnect();
m_list.DeleteAllItems();
OnBtnbl(); //遍歷顯示
//**************************************************
/* UpdateData(TRUE);
if(m_id.IsEmpty())
{
MessageBox("此項(xiàng)不能為空!");
}
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
_bstr_t sql;
sql="select * from st order by No ASC";
_RecordsetPtr m_pRecordset;
m_pRecordset=m_AdoConn.GetRecordSet((_bstr_t)sql);
try
{
m_pRecordset->Move(m_RecNo-1,vtMissing);
m_pRecordset->PutCollect("No",(_bstr_t)m_id);
m_pRecordset->PutCollect("Name",(_bstr_t)m_name);
m_pRecordset->PutCollect("Address",(_bstr_t)m_qita);
m_pRecordset->Update();
}
catch(...)
{
MessageBox("操作失敗");
return;
}
MessageBox("修改成功");
m_list.DeleteAllItems();
OnBtnbl(); */ //遍歷顯示
}
void CAdoSTDlg::OnBtndel()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
_bstr_t sql;
CString strsql;
// strsql.Format("delete from st where no = 66%s",m_id);
strsql.Format("delete from st where No = %s",m_id);
//sql="delete from st where No=66";
m_AdoConn.ExecuteSQL((_bstr_t)strsql);
//m_AdoConn.ExecuteSQL(sql);
m_AdoConn.ExitConnect();
m_list.DeleteAllItems();
OnBtnbl(); //遍歷顯示
/*UpdateData(TRUE);
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
_bstr_t sql;
sql="select * from st order by No ASC";
_RecordsetPtr m_pRecordset;
m_pRecordset=m_AdoConn.GetRecordSet((_bstr_t)sql);
CString m_id;
try
{
m_pRecordset->Move(m_RecNo-1,vtMissing);
m_pRecordset->Delete(adAffectCurrent);
m_pRecordset->Update();
}
catch(...)
{
MessageBox("操作失敗");
return;
}
MessageBox("刪除成功");
m_list.DeleteAllItems();
OnBtnbl(); *///遍歷顯示
}
void CAdoSTDlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
UpdateData(true);
int pos;
pos=m_list.GetSelectionMark();
m_id=m_list.GetItemText(pos,0);
m_name=m_list.GetItemText(pos,1);
m_qita=m_list.GetItemText(pos,2);
UpdateData(false);
*pResult = 0;
}
4.執(zhí)行SQL命令并取得結(jié)果記錄集
為了取得結(jié)果記錄集,我們定義一個(gè)指向Recordset對象的指針:_RecordsetPtrm_pRecordset;
并為其創(chuàng)建Recordset對象的實(shí)例: m_pRecordset.CreateInstance(”ADODB.Recordset“);
SQL命令的執(zhí)行可以采用多種形式,下面我們一進(jìn)行闡述。
(1)利用Connection對象的Execute方法執(zhí)行SQL命令
Execute方法的原型如下所示:
_RecordsetPtr Connection15::Execute ( _bstr_tCommandText, VARIANT * RecordsAffected,
long Options )
其中CommandText是命令字串,通常是SQL命令。
參數(shù)RecordsAffected是操作完成后所影響的行數(shù),
參數(shù)Options表示CommandText中內(nèi)容的類型,Options可以取如下值之一:
adCmdText:表明CommandText是文本命令
adCmdTable:表明CommandText是一個(gè)表名
adCmdProc:表明CommandText是一個(gè)存儲(chǔ)過程
adCmdUnknown:未知
Execute執(zhí)行完后返回一個(gè)指向記錄集的指針,下面我們給出具體代碼并作說明。
_variant_tRecordsAffected;
///執(zhí)行SQL命令:CREATE TABLE創(chuàng)建表格users,users包含四個(gè)字段:整形ID,字符串username,
整形old,日期型birthday
m_pConnection->Execute(”CREATE TABLE users(ID INTEGER,usernameTEXT,oldINTEGER,birthday
DATETIME)“,&RecordsAffected,adCmdText);
///往表格里面添加記錄
m_pConnection->Execute(”INSERT INTO users(ID,username,old,birthday) VALUES
(1, ''''Washington'''',25,''''1970/1/1'''')“,&RecordsAffected,adCmdText);
///將所有記錄old字段的值加一
m_pConnection->Execute(”UPDATE users SET old = old+1“,&RecordsAffected,adCmdText);
///執(zhí)行SQL統(tǒng)計(jì)命令得到包含記錄條數(shù)的記錄集
m_pRecordset = m_pConnection->Execute(”SELECT COUNT(*) FROM users“,&RecordsAffected,adCmdText);
_variant_tvIndex = (long)0;
_variant_tvCount = m_pRecordset->GetCollect(vIndex);///取得第一個(gè)字段的值放入vCount變量
上兩句可以寫成- _variant_tvCount = m_pRecordset->GetCollect((_variant_t)((long)0));
m_pRecordset->Close();///關(guān)閉記錄集
CString message;
message.Format(”共有%d條記錄“,vCount.lVal);
AfxMessageBox(message);///顯示當(dāng)前記錄條數(shù)
(2)利用Command對象來執(zhí)行SQL命令
_CommandPtrm_pCommand;
m_pCommand.CreateInstance(”ADODB.Command“);
_variant_tvNULL;
vNULL.vt = VT_ERROR;
vNULL.scode = DISP_E_PARAMNOTFOUND;///定義為無參數(shù)
m_pCommand->ActiveConnection = m_pConnection;///非常關(guān)鍵的一句,將建立的連接賦值給它
m_pCommand->CommandText = “SELECT * FROM users”;///命令字串
m_pRecordset = m_pCommand->Execute(&vNULL,&vNULL,adCmdText);///執(zhí)行命令,取得記錄集
在這段代碼中我們只是用Command對象來執(zhí)行了SELECT查詢語句,Command對象在進(jìn)行存儲(chǔ)過程的調(diào)用中能真正體現(xiàn)它的作用。下次我們將詳細(xì)介紹。
(3)直接用Recordset對象進(jìn)行查詢?nèi)〉糜涗浖?/font>
實(shí)例--
void CGmsaDlg::OnDBSelect()
{
// TODO: Add your control notification handler code here
_RecordsetPtr Rs1; //定義Recordset對象
_bstr_t Connect(“DSN=GMS;UID=sa;PWD=;”);//定義連接字符串
_bstr_t Source (“SELECT count(*) FROM buaa.mdb010”); //要執(zhí)行的SQL語句
::CoInitialize(NULL); //初始化Rs1對象
HRESUL hr = Rs1.CreateInstance( __uuidof( Recordset ) );
//省略對返回值hr的判斷
Rs1->Open( Source,
Connect,
adOpenForwardOnly,
adLockReadOnly,
-1 );
_variant_t temp=Rs1->GetCollect(_variant_t((long)0));
CStringstrTemp=(char* )(_bstr_t)temp;
MessageBox(“OK!”+strTemp);
}
例如
m_pRecordset->Open(“SELECT * FROM users”,
_variant_t((IDispatch *)m_pConnection,true),
adOpenStatic,
adLockOptimistic,
adCmdText);
5.記錄集的遍歷、更新
根據(jù)我們剛才通過執(zhí)行SQL命令建立好的users表,它包含四個(gè)字段:ID,username,old,birthday
以下的代碼實(shí)現(xiàn):打開記錄集,遍歷所有記錄,刪除第一條記錄,添加三條記錄,移動(dòng)光標(biāo)到第二條記錄,
更改其年齡,保存到數(shù)據(jù)庫。
_variant_tvUsername,vBirthday,vID,vOld;
_RecordsetPtrm_pRecordset;
m_pRecordset.CreateInstance(“ADODB.Recordset”);
m_pRecordset->Open(“SELECT * FROM users”,
_variant_t((IDispatch*)m_pConnection,true),
adOpenStatic,
adLockOptimistic,
adCmdText);
while(!m_pRecordset->adoEOF)
{
vID = m_pRecordset->GetCollect(_variant_t((long)0));///取得第1列的值,從0開始計(jì)數(shù),
///您也可以直接給出列的名稱,如下一行
vUsername = m_pRecordset->GetCollect(“username”);///取得username字段的值
vOld = m_pRecordset->GetCollect(“old”);
vBirthday = m_pRecordset->GetCollect(“birthday”);
///在DEBUG方式下的OUTPUT窗口輸出記錄集中的記錄
if(vID.vt != VT_NULL &&vUsername.vt != VT_NULL &&vOld.vt != VT_NULL &&vBirthday.vt
!= VT_NULL)
TRACE(“id:%d,姓名:%s,年齡:%d,生日:%s “,
vID.lVal,
(LPCTSTR)(_bstr_t)vUsername,
vOld.lVal,
(LPCTSTR)(_bstr_t)vBirthday);
m_pRecordset->MoveNext();///移到下一條記錄
}
m_pRecordset->MoveFirst();///移到首條記錄
m_pRecordset->Delete(adAffectCurrent);///刪除當(dāng)前記錄
///添加三條新記錄并賦值
for(inti=0;i<3;i++)
{
m_pRecordset->AddNew();///添加新記錄
m_pRecordset->PutCollect(”ID“,_variant_t((long)(i+10)));
m_pRecordset->PutCollect(”username“,_variant_t(”葉利欽“));
m_pRecordset->PutCollect(”old“,_variant_t((long)71));
m_pRecordset->PutCollect(”birthday“,_variant_t(”1930-3-15“));
}
m_pRecordset->Move(1,_variant_t((long)adBookmarkFirst));///從第一條記錄往下移動(dòng)一條記錄,即移動(dòng)
到第二條記錄處
m_pRecordset->PutCollect(_variant_t(”old“),_variant_t((long)45));///修改其年齡
m_pRecordset->Update();///保存到庫中
備注:多次查詢可把查詢過程做成一個(gè)函數(shù)ExecuteSQL讓m_pRecordset獲得連接指針m_pConnection查詢結(jié)果
void ExecuteSQL(_ConnectionPtrm_pConnection, _RecordsetPtrm_pRecordset,CStringstrSql)
{
//執(zhí)行Select 語句
BSTR bstrSQL = strSql.AllocSysString();
try
{
m_pRecordset->Open(bstrSQL,(IDispatch*)m_pConnection,adOpenDynamic,adLockOptimistic,
adCmdText);
//adOpenDynamic:動(dòng)態(tài) adLockOptimistic樂觀封鎖法 adCmdText:文本查詢語句
}
catch(_com_error error)
{
CStringerrorMessage;
errorMessage.Format(”%s“,(LPTSTR)error.Description());
AfxMessageBox(errorMessage);
}
}
//出錯(cuò)處理:
3127--沒有找到目標(biāo)表
3092--目標(biāo)表已經(jīng)存在
例如:
catch(const _com_error e)
{
AfxMessageBox(e.Description());
long errorCode=e.WCode();
if(3127==errorCode) AfxMessageBox(”表不存在“);
if(3092==errorCode) AfxMessageBox(”表已經(jīng)存在“);
return FALSE;
}
聯(lián)系客服