2008年(909)
分类:
2008-05-06 21:34:43
下载本文配套工程
我最近正在学习ADO,并试着做了一个简单的SQL Plus,在此过程中有一些经验希望和大家分享。
代码运行效果图如下:
编译时要在stdafx.h中指定正确的路径:#import "msado15.dll" no_namespace rename("EOF","adoEOF")
一、连接数据库
在此例子中我连接了3种常用的数据库:Access,Oracle,Sql server。关键是连接字符
串的不同,如下所示:
HRESULT hr; _ConnectionPtr m_pConnTemp; UpdateData(); //Oracle 的连接: CString strConnection = "Provider=MSDAORA;Data Source=" m_dbserver ";User ID=" m_username "; Password=" m_passwd; //Sql server的连接: CString strConnection = "Provider=SQLOLEDB.1;Data Source=" m_dbserver ";Initial Catalog=" m_initDb //初始时连接的数据库 ";User ID=" m_username "; PWD=" m_passwd; //Access 的连接: CString strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" m_filename; try { hr = m_pConnTemp.CreateInstance("ADODB.Connection"); if(SUCCEEDED(hr)) { hr=m_pConnTemp->Open((_bstr_t)strConnection,"","",-1); OnOK(); } } catch(_com_error e) { CCommon common; AfxMessageBox(common.DisplayAdoError(m_pConnTemp)); }二 、错误消息的获得
CString CCommon::DisplayAdoError(_ConnectionPtr m_pConnection) { long errorcount = m_pConnection->GetErrors()->GetCount(); _bstr_t add; CString ErrorMessage,temp; for(short i=0; i三、得到"update","insert"操作的记录数:GetErrors()->GetItem(_variant_t((short)i))->GetDescription(); temp = (char *)add; ErrorMessage = temp; } return ErrorMessage; }
_variant_t fieldCount; VariantInit (&fieldCount); MainFrame->m_pUserSet = MainFrame->m_commandptr->Execute(&fieldCount,NULL,adCmdUnknown); if(!MainFrame->m_pUserSet ->State) //当是Select操作时此条件为假 { //fieldCount.lVal中保存的就是"update","insert"操作的记录数 View->ShowResult(fieldCount.lVal); } VariantClear(&fieldCount);
listTable.ShowWindow (SW_SHOW); listTable.DeleteAllItems(); int nColumnCount = listTable.GetHeaderCtrl()->GetItemCount(); // 删除所有的列 for (i=0;i < nColumnCount;i ) { listTable.DeleteColumn (0); } int fieldCount=Rsc->Fields ->Count; //得到字段的总数 int fieldLength = 0; FieldPtr m_fieldCtl; for(i=0;iFields ->GetItem(long(i)); //得到字段名 fieldLength = m_fieldCtl->DefinedSize*10; if (fieldLength >500) //when field is very long then trim it { fieldLength = 500; } else if (fieldLength < 50) { fieldLength = 50; } if (fieldLength Name.length ()*12) { fieldLength = m_fieldCtl->Name.length ()*12; } listTable.InsertColumn(i,m_fieldCtl->Name,LVCFMT_LEFT,fieldLength); } int nItem = 0; _variant_t varValue; _bstr_t bstrValue; while(!Rsc->adoEOF) { m_fieldCtl = Rsc->Fields ->GetItem(long(0)); //得到字段的值 varValue = m_fieldCtl->Value; if (varValue.vt == VT_NULL) //注意:当值为空时,直接插入会导致异常 { bstrValue = ""; } else { bstrValue=varValue; } nItem=listTable.InsertItem(0xffff,bstrValue); //fisrt value for(i=1;i Fields ->GetItem(long(i)); varValue = m_fieldCtl->Value; if (varValue.vt == VT_NULL) { bstrValue = ""; } else { bstrValue=varValue; } listTable.SetItem(nItem,i,1,bstrValue,NULL,0,0,0); } Rsc->MoveNext (); }
作者邮箱:gaochun@ec.necsi-sh.nec.com.cn 或 firstyi2002@yahoo.com.cn
下载本文示例代码